Recursively Populate Parent n level - node.js
I have a category Model which looks like this
const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const category = {
name: {
type: String,
required: true,
trim: true,
max: 32,
unique: true,
},
subCategories: [
{
type: Schema.Types.ObjectId,
ref: "Category",
},
],
parent: {
type: Schema.Types.ObjectId,
ref: "Category",
},
products: [
{
type: ObjectId,
ref: "Product",
},
],
slug: {
type: String,
required: "URL can't be empty",
unique: true,
},
};
const categorySchema = new Schema(category, { timestamps: true });
//Validate the slug to ensure proper url is given
categorySchema.path("slug").validate((val) => {
urlRegex =
/(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-/]))?/;
return urlRegex.test(val);
}, "Invalid URL.");
const autoPopulateChildren = function (next) {
this.populate("subCategories");
next();
};
categorySchema
.pre("findOne", autoPopulateChildren)
.pre("findById", autoPopulateChildren)
.pre("find", autoPopulateChildren);
const Category = mongoose.model("Category", categorySchema);
module.exports = Category;
I would like to recursively populate its parent.
Right now, I have a data that looks like this
Main
-> Computers & Accessories
-> Components
-> Motherboard
When I query Motherboard category, I would like it to return back all its parents (all the way up to Main category). Something like this
{
"subCategories": [],
"products": [],
"_id": "62baca1a1ffdc142085bca80",
"name": "Motherboard",
"parent": {
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62baca1a1ffdc142085bca80",
"name": "Motherboard",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/motherboard",
"createdAt": "2022-06-28T09:30:02.040Z",
"updatedAt": "2022-06-28T09:30:02.040Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bac9a24bd73045dcb563d7",
"name": "RAM",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/ram",
"createdAt": "2022-06-28T09:28:02.643Z",
"updatedAt": "2022-06-28T09:28:02.643Z",
"__v": 0
}
],
"products": [],
"_id": "62bac5af6b6581786cb192e4",
"name": "components",
"parent": {
"subCategories": [
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62baca1a1ffdc142085bca80",
"name": "Motherboard",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/motherboard",
"createdAt": "2022-06-28T09:30:02.040Z",
"updatedAt": "2022-06-28T09:30:02.040Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bac9a24bd73045dcb563d7",
"name": "RAM",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/ram",
"createdAt": "2022-06-28T09:28:02.643Z",
"updatedAt": "2022-06-28T09:28:02.643Z",
"__v": 0
}
],
"products": [],
"_id": "62bac5af6b6581786cb192e4",
"name": "components",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007/category/components",
"createdAt": "2022-06-28T09:11:11.226Z",
"updatedAt": "2022-06-28T09:11:11.226Z",
"__v": 0
},
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62bacae4da4c372c48c4a996",
"name": "Huawei",
"parent": "62bac6696b6581786cb192e7",
"slug": "http://localhost:4007/category/huawei",
"createdAt": "2022-06-28T09:33:24.218Z",
"updatedAt": "2022-06-28T09:33:24.218Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bacb137e6e0b6ac850b9ce",
"name": "Apple",
"parent": "62bac6696b6581786cb192e7",
"slug": "http://localhost:4007/category/apple",
"createdAt": "2022-06-28T09:34:11.549Z",
"updatedAt": "2022-06-28T09:34:11.549Z",
"__v": 0
}
],
"products": [],
"_id": "62bac6696b6581786cb192e7",
"name": "laptop",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007//category/laptop",
"createdAt": "2022-06-28T09:14:17.650Z",
"updatedAt": "2022-06-28T09:14:17.650Z",
"__v": 0
},
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62bacb65045848303cd21b67",
"name": "Gaming",
"parent": "62bac8016b6581786cb192f0",
"slug": "http://localhost:4007/category/gaming",
"createdAt": "2022-06-28T09:35:33.414Z",
"updatedAt": "2022-06-28T09:35:33.414Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bacc72e84e007314a97abe",
"name": "DIY",
"parent": "62bac8016b6581786cb192f0",
"slug": "http://localhost:4007/category/diy",
"createdAt": "2022-06-28T09:40:02.359Z",
"updatedAt": "2022-06-28T09:40:02.359Z",
"__v": 0
}
],
"products": [],
"_id": "62bac8016b6581786cb192f0",
"name": "Desktop",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007//category/components",
"createdAt": "2022-06-28T09:21:05.807Z",
"updatedAt": "2022-06-28T09:21:05.807Z",
"__v": 0
}
],
"products": [],
"_id": "62bac35ba30786989841809b",
"name": "Computers & Accessories",
"parent": {
"subCategories": [
{
"subCategories": [
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62baca1a1ffdc142085bca80",
"name": "Motherboard",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/motherboard",
"createdAt": "2022-06-28T09:30:02.040Z",
"updatedAt": "2022-06-28T09:30:02.040Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bac9a24bd73045dcb563d7",
"name": "RAM",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/ram",
"createdAt": "2022-06-28T09:28:02.643Z",
"updatedAt": "2022-06-28T09:28:02.643Z",
"__v": 0
}
],
"products": [],
"_id": "62bac5af6b6581786cb192e4",
"name": "components",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007/category/components",
"createdAt": "2022-06-28T09:11:11.226Z",
"updatedAt": "2022-06-28T09:11:11.226Z",
"__v": 0
},
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62bacae4da4c372c48c4a996",
"name": "Huawei",
"parent": "62bac6696b6581786cb192e7",
"slug": "http://localhost:4007/category/huawei",
"createdAt": "2022-06-28T09:33:24.218Z",
"updatedAt": "2022-06-28T09:33:24.218Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bacb137e6e0b6ac850b9ce",
"name": "Apple",
"parent": "62bac6696b6581786cb192e7",
"slug": "http://localhost:4007/category/apple",
"createdAt": "2022-06-28T09:34:11.549Z",
"updatedAt": "2022-06-28T09:34:11.549Z",
"__v": 0
}
],
"products": [],
"_id": "62bac6696b6581786cb192e7",
"name": "laptop",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007//category/laptop",
"createdAt": "2022-06-28T09:14:17.650Z",
"updatedAt": "2022-06-28T09:14:17.650Z",
"__v": 0
},
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62bacb65045848303cd21b67",
"name": "Gaming",
"parent": "62bac8016b6581786cb192f0",
"slug": "http://localhost:4007/category/gaming",
"createdAt": "2022-06-28T09:35:33.414Z",
"updatedAt": "2022-06-28T09:35:33.414Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bacc72e84e007314a97abe",
"name": "DIY",
"parent": "62bac8016b6581786cb192f0",
"slug": "http://localhost:4007/category/diy",
"createdAt": "2022-06-28T09:40:02.359Z",
"updatedAt": "2022-06-28T09:40:02.359Z",
"__v": 0
}
],
"products": [],
"_id": "62bac8016b6581786cb192f0",
"name": "Desktop",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007//category/components",
"createdAt": "2022-06-28T09:21:05.807Z",
"updatedAt": "2022-06-28T09:21:05.807Z",
"__v": 0
}
],
"products": [],
"_id": "62bac35ba30786989841809b",
"name": "Computers & Accessories",
"parent": "62bac6eddfe90a7c09873d92",
"slug": "http://localhost:4007/category/computers&accessories",
"createdAt": "2022-06-28T09:01:15.666Z",
"updatedAt": "2022-06-28T09:01:15.666Z",
"__v": 0
}
],
"products": [],
"_id": "62bac6eddfe90a7c09873d92",
"name": "Main Shop Name",
"parent": null,
"slug": "http://localhost:4007/category/main",
"createdAt": "2022-06-28T09:01:15.666Z",
"updatedAt": "2022-06-28T09:01:15.666Z",
"__v": 0
},
"slug": "http://localhost:4007/category/computers&accessories",
"createdAt": "2022-06-28T09:01:15.666Z",
"updatedAt": "2022-06-28T09:01:15.666Z",
"__v": 0
},
"slug": "http://localhost:4007/category/components",
"createdAt": "2022-06-28T09:11:11.226Z",
"updatedAt": "2022-06-28T09:11:11.226Z",
"__v": 0
},
"slug": "http://localhost:4007/category/motherboard",
"createdAt": "2022-06-28T09:30:02.040Z",
"updatedAt": "2022-06-28T09:30:02.040Z",
"__v": 0
}
Following is my code
const populateParents = async (node) => {
if (node.parent) {
let newNode = await Category.populate(node, { path: "parent" });
return populateParents(newNode.parent);
}
return node;
};
//Routes
router.get("/categories/:categoryId", [RequireSignIn], async (req, res) => {
try {
const { categoryId } = req.params;
const category = await Category.findOne({ _id: categoryId });
const populatedCategories = await populateParents(category);
return res.status(200).send(populatedCategories);
} catch (error) {
return res.status(500).send(error);
}
});
What I am getting back is only the Main category in response.
{
"subCategories": [
{
"subCategories": [
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62baca1a1ffdc142085bca80",
"name": "Motherboard",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/motherboard",
"createdAt": "2022-06-28T09:30:02.040Z",
"updatedAt": "2022-06-28T09:30:02.040Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bac9a24bd73045dcb563d7",
"name": "RAM",
"parent": "62bac5af6b6581786cb192e4",
"slug": "http://localhost:4007/category/ram",
"createdAt": "2022-06-28T09:28:02.643Z",
"updatedAt": "2022-06-28T09:28:02.643Z",
"__v": 0
}
],
"products": [],
"_id": "62bac5af6b6581786cb192e4",
"name": "components",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007/category/components",
"createdAt": "2022-06-28T09:11:11.226Z",
"updatedAt": "2022-06-28T09:11:11.226Z",
"__v": 0
},
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62bacae4da4c372c48c4a996",
"name": "Huawei",
"parent": "62bac6696b6581786cb192e7",
"slug": "http://localhost:4007/category/huawei",
"createdAt": "2022-06-28T09:33:24.218Z",
"updatedAt": "2022-06-28T09:33:24.218Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bacb137e6e0b6ac850b9ce",
"name": "Apple",
"parent": "62bac6696b6581786cb192e7",
"slug": "http://localhost:4007/category/apple",
"createdAt": "2022-06-28T09:34:11.549Z",
"updatedAt": "2022-06-28T09:34:11.549Z",
"__v": 0
}
],
"products": [],
"_id": "62bac6696b6581786cb192e7",
"name": "laptop",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007//category/laptop",
"createdAt": "2022-06-28T09:14:17.650Z",
"updatedAt": "2022-06-28T09:14:17.650Z",
"__v": 0
},
{
"subCategories": [
{
"subCategories": [],
"products": [],
"_id": "62bacb65045848303cd21b67",
"name": "Gaming",
"parent": "62bac8016b6581786cb192f0",
"slug": "http://localhost:4007/category/gaming",
"createdAt": "2022-06-28T09:35:33.414Z",
"updatedAt": "2022-06-28T09:35:33.414Z",
"__v": 0
},
{
"subCategories": [],
"products": [],
"_id": "62bacc72e84e007314a97abe",
"name": "DIY",
"parent": "62bac8016b6581786cb192f0",
"slug": "http://localhost:4007/category/diy",
"createdAt": "2022-06-28T09:40:02.359Z",
"updatedAt": "2022-06-28T09:40:02.359Z",
"__v": 0
}
],
"products": [],
"_id": "62bac8016b6581786cb192f0",
"name": "Desktop",
"parent": "62bac35ba30786989841809b",
"slug": "http://localhost:4007//category/components",
"createdAt": "2022-06-28T09:21:05.807Z",
"updatedAt": "2022-06-28T09:21:05.807Z",
"__v": 0
}
],
"products": [],
"_id": "62bac35ba30786989841809b",
"name": "Computers & Accessories",
"parent": "62bac6eddfe90a7c09873d92",
"slug": "http://localhost:4007/category/computers&accessories",
"createdAt": "2022-06-28T09:01:15.666Z",
"updatedAt": "2022-06-28T09:01:15.666Z",
"__v": 0
}
],
"products": [],
"_id": "62bac6eddfe90a7c09873d92",
"name": "Main Shop Name",
"parent": null,
"slug": "http://localhost:4007/category/main",
"createdAt": "2022-06-28T09:01:15.666Z",
"updatedAt": "2022-06-28T09:01:15.666Z",
"__v": 0
}
If I write the function without recursion , it works
const populateParents2 = async (node) => {
const newNode = await Category.populate(node, { path: "parent" });
const newNode2 = await Category.populate(newNode.parent, { path: "parent" });
const newNode3 = await Category.populate(newNode2.parent, { path: "parent" });
return newNode;
};
So appreciate if someone can point out how to write populateParents function recursively or is there another better way to do this
Thank you
Question very similar to this question Create a deeply nested object
Btw found the solution for this question
const populateParents = async (node) => {
if (node.parent === null) {
return node;
}
const parent = await Category.findById(node.parent).select("-subCategories");
node.parent = parent;
await populateParents(node.parent);
return node;
};
//Routes
router.get("/categories/:categoryId", async (req, res) => {
try {
const { categoryId } = req.params;
const category = await Category.findOne({ _id: categoryId }).select(
"-subCategories"
);
const populatedCategories = await populateParents(category);
return res.status(200).send(populatedCategories);
} catch (error) {
return res.status(500).send(error);
}
});
Related
Remove nested categories in mongo
I want when a category is deleted. All its child categories and its own categories will be deleted. For example, I want if the web development category is deleted. All its child categories (delete Django and Django Channel) { "statusCode": 200, "data": { "categories": [ { "_id": "62fdfb567bb46dcf93b3717f", "title": "Web development", "parent": null, "position": "important", "slug": "-eb-development", "createdAt": "2022-08-18T08:41:58.826Z", "updatedAt": "2022-08-18T08:41:58.826Z", "children": [ { "_id": "62fdfb677bb46dcf93b3718d", "title": "Django", "parent": "62fdfb567bb46dcf93b3717f", "position": "unimportant", "slug": "-jango", "createdAt": "2022-08-18T08:42:15.557Z", "updatedAt": "2022-08-18T08:42:15.557Z", "children": [ { "_id": "62fdfb857bb46dcf93b371a1", "title": "Django chennels", "parent": "62fdfb677bb46dcf93b3718d", "position": "unimportant", "slug": "-jango-chennels", "createdAt": "2022-08-18T08:42:45.665Z", "updatedAt": "2022-08-18T08:42:45.665Z", "children": [], "id": "62fdfb857bb46dcf93b371a1" } ], "id": "62fdfb677bb46dcf93b3718d" } ], "id": "62fdfb567bb46dcf93b3717f" } ] } } I wrote a code for this which does not work properly and removes only one child from the desired category. const category = await this.checkExistCategory(id); const deleteResult = await Category.deleteMany({ $or: [{ _id: category._id }, { parent: category._id }], }); Thank you very much for helping me!!
Aggregation query
Node js using mongoose as ORM. I have set of documents like below I want to calculate the average time for createdAt in ISO String(format) field in duration of hours on grouping the category field. I have tried many ways to use aggregate but couldn't get the result. [{ "_id": { "$oid": "62dfc2cf25735e8b1b475ff1" }, "numLikes": 0, "numViews": 0, "numShares": 0, "hasUserLiked": false, "title": "sample-broadcast", "description": "broadcast-dewscription", "projectId": { "$oid": "62d903a5dade1714382b27af" }, "content": [ { "_id": { "$oid": "62dfc2cf25735ee18d475ff2" }, "downloadLink": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/51daead4-1134-4921-a544-fea845f03d1c/uploadbroadcast/1658831544", "label": "lance-anderson-QdAAasrZhdk-unsplash (1).jpg", "contentType": "jpeg" } ], "delivery": "scheduleBroadcast", "category": "GENERAL_UPDATES", "groupId": "51daead4-1134-4921-a544-fea845f03d1c", "author": { "userId": "83314517-9326-430f-9c4e-8fedb050e6b0", "profilePic": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/4f670832-dfd7-43ee-a6ad-e2f43f48df6a/uploadprofilepic/1658239806", "name": "Biswajit Rout" }, "projectLogo": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/4f670832-dfd7-43ee-a6ad-e2f43f48df6a/uploadcompanylogo%2A/1658239764", "createdAt": { "$date": { "$numberLong": "1658831567577" } }, "updatedAt": { "$date": { "$numberLong": "1658831567577" } }, "__v": 0 },{ "_id": { "$oid": "62dfebae25735e015f476dfb" }, "numLikes": 0, "numViews": 0, "numShares": 0, "hasUserLiked": false, "title": "testing-broadcast", "description": "testing-description", "projectId": { "$oid": "62d903a5dade1714382b27af" }, "content": [ { "_id": { "$oid": "62dfebae25735e291c476dfc" }, "downloadLink": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/51daead4-1134-4921-a544-fea845f03d1c/projectimages0/1658842001", "label": "lance-anderson-QdAAasrZhdk-unsplash (1).jpg", "contentType": "jpeg" }, { "_id": { "$oid": "62dfebae25735e0321476dfd" }, "downloadLink": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/51daead4-1134-4921-a544-fea845f03d1c/projectimages1/1658842024", "label": "Get_Started_With_Smallpdf.pdf", "contentType": "pdf" } ], "delivery": "immediate", "link": "http://localhost:3000", "category": "GENERAL_UPDATES", "groupId": "51daead4-1134-4921-a544-fea845f03d1c", "author": { "userId": "83314517-9326-430f-9c4e-8fedb050e6b0", "profilePic": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/4f670832-dfd7-43ee-a6ad-e2f43f48df6a/uploadprofilepic/1658239806", "name": "Biswajit Rout" }, "projectLogo": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/4f670832-dfd7-43ee-a6ad-e2f43f48df6a/uploadcompanylogo%2A/1658239764", "createdAt": { "$date": { "$numberLong": "1658842030827" } }, "updatedAt": { "$date": { "$numberLong": "1658842030827" } }, "__v": 0 },{ "_id": { "$oid": "62e144677fc76b0373f40152" }, "numLikes": 0, "numViews": 0, "numShares": 0, "hasUserLiked": false, "title": "Broker Offer-1", "description": "50% off on the membership for early birds. \n\nOffer Applied to first fifty users only", "projectId": { "$oid": "62d903a5dade1714382b27af" }, "content": [ { "_id": { "$oid": "62e144677fc76b2b79f40153" }, "downloadLink": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/51daead4-1134-4921-a544-fea845f03d1c/projectimages0/1658930275", "label": "50-off-PNG-Picture.png", "contentType": "png" } ], "delivery": "immediate", "link": "", "category": "OFFER_BROKERS", "groupId": "51daead4-1134-4921-a544-fea845f03d1c", "author": { "userId": "83314517-9326-430f-9c4e-8fedb050e6b0", "profilePic": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/4f670832-dfd7-43ee-a6ad-e2f43f48df6a/uploadprofilepic/1658239806", "name": "Biswajit Rout" }, "projectLogo": "https://builder-broadcast-media.s3.ap-south-1.amazonaws.com/builder-broadcast-media/4f670832-dfd7-43ee-a6ad-e2f43f48df6a/uploadcompanylogo%2A/1658239764", "createdAt": { "$date": { "$numberLong": "1658930279871" } }, "updatedAt": { "$date": { "$numberLong": "1658930279871" } }, "__v": 0 }] My expected result should be like this { OFFER_BROKERS: 5 <hrs>, GENERAL_UPDATES : 4 <hrs> }
Do you want to convert milliseconds to real time and give it to orm
How to add orders array in product
Whenever a customer checks out its saves an order that has products ordered by a customer and the product id, quantity and customers details like delivery address and customer phone number. I want the same details to be added to all products in that order also so that the seller can also see that his product has been ordered This i can achieve using each product's id in the orders since every product has its ID . But i dont know how to map the order's products id's and find the products in the products schema then add to them an array called orders. This is how my orders schema looks like after an order has been placed { "allOrders": [ { "_id": "6249ee9baa59aceb7d88f91d", "placedby": "624471321dff6794a802431c", "fullname": "Collins Jimu", "deliveryaddress": "cnr fourth and herbet chitepo", "phonenumber": "0773468496", "whatsappphonenumber": "0773468496", "ordersList": [ { "name": "Hp 200 G4Core I5", "qty": 1, "price": 560, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648734312/cwynmzauqqnylrwsgejy.jpg", "id": "6245b0c09390975e16263136" }, { "name": "bed", "qty": 1, "price": 160, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648732217/dtrb8saj0ellgyrcjpyy.jpg", "id": "6245a88cf22df558d8d69162" }, { "name": "Sunglass", "qty": 1, "price": 6, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648738341/rtpiptqc1le6kywmuisf.jpg", "id": "6245c03bf22df558d8d6a739" }, { "name": "sofas", "qty": 1, "price": 890, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648732837/xae655b5e9wovodfkvqn.jpg", "id": "6245aacdf22df558d8d6939f" } ], "paymentmethod": "cashondeliver", "orderstatus": "placed", "createdAt": "2022-04-03T18:59:39.681Z", "updatedAt": "2022-04-03T18:59:39.681Z", "__v": 0 }, { "_id": "6249fdc602cefac4faa36dde", "placedby": "624471321dff6794a802431c", "fullname": "My MUM", "deliveryaddress": "123 HARARE STREET", "phonenumber": "0773550804", "whatsappphonenumber": "0773550804", "ordersList": [ { "name": "out door benches", "qty": 1, "price": 25, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648736078/in8rumwcm6rrebrmgb1q.jpg", "id": "6245b792be41db13f9220867" }, { "name": "hammer", "qty": 1, "price": 10, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648735570/joceetdkx4penomtab8s.jpg", "id": "6245b5849390975e16263647" }, { "name": "Watches", "qty": 1, "price": 4, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648735962/r4jmwlj7ltgc0njdtfdc.jpg", "id": "6245b71abe41db13f92207ac" }, { "name": "iPhone X", "qty": 1, "price": 350, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648729600/ekcb86lmtkr0uniirb2i.jpg", "id": "62459fc3be41db13f921f27a" }, { "name": "REFRIDGERATOR", "qty": 1, "price": 370, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648731962/fjrlvfnotdbonqnt9pjn.jpg", "id": "6245a750be41db13f921f796" } ], "paymentmethod": "cashondeliver", "orderstatus": "placed", "createdAt": "2022-04-03T20:04:22.349Z", "updatedAt": "2022-04-03T20:04:22.349Z", "__v": 0 }, { "_id": "624a12ea02cefac4faa431fd", "placedby": "624471321dff6794a802431c", "fullname": "Munyaradzi Makosa", "deliveryaddress": "cnr fourth and herbet", "phonenumber": "0777727363663", "whatsappphonenumber": "0777727363663", "ordersList": [ { "name": "Wheels", "qty": 1, "price": 35, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648741496/xs9zpht0rhxpijrzyqrz.jpg", "id": "6245cc859390975e162657ce" }, { "name": "MacBook Pro 2021", "qty": 1, "price": 1250, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648731661/h0dcvvhwntdy06mzgpah.webp", "id": "6245a6649390975e16262737" }, { "name": "electric kettle", "qty": 1, "price": 22, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648734446/tyrdlrayn3opm7gagwmi.jpg", "id": "6245b1239390975e162631e3" } ], "paymentmethod": "cashondeliver", "orderstatus": "placed", "createdAt": "2022-04-03T21:34:34.721Z", "updatedAt": "2022-04-03T21:34:34.721Z", "__v": 0 }, { "_id": "624aa7cd02cefac4faa4750c", "placedby": "624aa7a102cefac4faa474f3", "fullname": "Ryan Katayi", "deliveryaddress": "4164 Gwabalanda", "phonenumber": "0718518438", "whatsappphonenumber": "0718518438", "ordersList": [ { "name": "Budi 2017", "qty": 1, "price": 250, "imgUrl": "/assets/images/products/Automotive/2.Audi2017.png", "id": "6270512109915791" } ], "paymentmethod": "cashondeliver", "orderstatus": "placed", "createdAt": "2022-04-04T08:09:49.618Z", "updatedAt": "2022-04-04T08:09:49.618Z", "__v": 0 }, { "_id": "624c0e770d2cf94693988609", "placedby": "624aa7a102cefac4faa474f3", "fullname": "Ryan Katayi", "deliveryaddress": "4164 Gwabalanda", "phonenumber": "0718518438", "whatsappphonenumber": "0778687452", "ordersList": [ { "name": "Nike Airforce", "qty": 2, "price": 40, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1649082553/hoodaley8bzrwa8xi2tr.jpg", "id": "624b01250d2cf94693982652" }, { "name": "iPhone X", "qty": 1, "price": 350, "imgUrl": "https://res.cloudinary.com/kwingy/image/upload/v1648729600/ekcb86lmtkr0uniirb2i.jpg", "id": "62459fc3be41db13f921f27a" } ], "paymentmethod": "cashondeliver", "orderstatus": "placed", "createdAt": "2022-04-05T09:40:07.719Z", "updatedAt": "2022-04-05T09:40:07.719Z", "__v": 0 } ] } i have managed to get the ids of all the orders. But my challenge is i am stuck with only the products ids not sure how to use them and find each products and then patch them with an orders details array const sellerProductsOrdered = asyncHandler (async (req, res) => { const Orders = await Order.find(); const ordersList = Orders.map(order => { return order }) const ordersListProductsIds = ordersList.map(product => { return product.id }) console.log(ordersListProductsIds); })
Retrieve object information within an array with mongoose
I'm making an API Rest with node, express, typescript and mongoose. I have a method GET that return this result: { "success": true, "status": 200, "message": "categories listed", "data": [ { "_id": "612650e55fe1ce0de138e2af", "products": [ { "_id": "612650e55fe1ce0de138e2b0", "productID": { "reviews": [ "611e61ba8cb43f7454787ebb", "611e62008cb43f7454787ebc" ], "_id": "610b18f3e2244a187b36f2d7", "title": "PS4", "description": "La mejor consola del mercado del mundo, mundial", "photo": "https://amazon-clone-jparrot.s3.amazonaws.com/1628123519052", "price": 400, "stockQuantity": 23, "__v": 0, "category": "60fc6454b68717acc239cc6a", "owner": "610b9ed8763da4308223aae0", "averageRating": null, "id": "610b18f3e2244a187b36f2d7" }, "quantity": 1, "price": 400 } ], "owner": { "_id": "611d2d39dfcc705972c1ccb8", "name": "Jaume", "email": "jaumeparrot2#gmail.com", "password": "$2a$10$Rv9Rzrff6578feCdDjyeKuarKCSHYRqKp5n5wTi2IWtcLBOupvPgu", "__v": 0, "address": "611e9ccdf47c7a7a9cb1d5d9" }, "estimatedDelivery": "Wednesday September 1st", "__v": 0 } ] } The problem is that I need to retrieve the object "owner", that is, I need to recover this json: { "success": true, "status": 200, "message": "categories listed", "data": [ { "_id": "612650e55fe1ce0de138e2af", "products": [ { "_id": "612650e55fe1ce0de138e2b0", "productID": { "reviews": [ "611e61ba8cb43f7454787ebb", "611e62008cb43f7454787ebc" ], "_id": "610b18f3e2244a187b36f2d7", "title": "PS4", "description": "La mejor consola del mercado del mundo, mundial", "photo": "https://amazon-clone-jparrot.s3.amazonaws.com/1628123519052", "price": 400, "stockQuantity": 23, "__v": 0, "category": "60fc6454b68717acc239cc6a", "owner": { "_id": "611d2d39dfcc705972c1ccb8", "name": "Jaume", "about": "My na is Jaume", "__v": 0 }, "averageRating": null, "id": "610b18f3e2244a187b36f2d7" }, "quantity": 1, "price": 400 } ], "owner": { "_id": "611d2d39dfcc705972c1ccb8", "name": "Jaume", "email": "jaumeparrot2#gmail.com", "password": "$2a$10$Rv9Rzrff6578feCdDjyeKuarKCSHYRqKp5n5wTi2IWtcLBOupvPgu", "__v": 0, "address": "611e9ccdf47c7a7a9cb1d5d9" }, "estimatedDelivery": "Wednesday September 1st", "__v": 0 } ] } For generate this JSON, I'm using this method: https://github.com/jparrot92/amazon-clone-back/blob/master/src/controllers/order.ts
To retrieve you should use data.owner. This will give owner details as object.
This is the solution: const products = await Order.find({ owner: req.user._id }) .populate('owner') .populate({ path: 'products.productID', populate: { path: 'owner', model: 'Owner', }, }) .exec();
Edit (Update) Specific value in MongoDB Document
I Want to update Only the value of payStatus data : { "profile": { "guestName": "Hussein Khalil", "mobile": "01223550119", "email": "husseinkhalil33#gmail.com" }, "hotelRoomingList": { "child": { "childAges": [ 2, 4 ], "childNo": 2 }, "hotelStatus": "Not Confirmed", "roomsNo": 3, "adultsNo": 2, "travelAgent": "Nilsen", "hotelConfNo": "G1B412", "roomingNotes": "Some rooming Notes", "roomingList": { "_id": "604b79ecb102efdea80a0698", "roomingName": "Pyramids", "roomingDescription": "this is Pyramids travels", "revenueMonth": "jul", "startedDate": "2021-03-12T14:25:48.830Z", "__v": 0, "id": "604b79ecb102efdea80a0698" }, "hotel": { "_id": "604d511964927d1759884e36", "hotelName": "Concorde Front", "__v": 0, "id": "604d511964927d1759884e36" }, "roomType": { "_id": "604d516564927d1759884e37", "roomType": "double", "__v": 0, "id": "604d516564927d1759884e37" }, "mealPlane": { "_id": "604aa5a7246f847df848c796", "mealPlane": "SAL", "__v": 0, "id": "604aa5a7246f847df848c796" }, "nights": 8, "arrivalDate": "2021-03-27T22:00:00.000Z", "departureDate": "2021-04-04T22:00:00.000Z" }, "customerAccount": { "payStatus": "not-gura-not-sure", "fullPay": 3000, "hotelCost": 2050, "transportCost": 150, "otherCost": 50, "paid": 1250, "optionDate": "2021-04-05T22:00:00.000Z", "customerNotes": "some customerNotes", "restOfPay": 1750, "profit": 750 }, "transportation": { "transport": { "_id": "604b61b6aad5fab0f3c0d40d", "transportType": "Bus", "__v": 0, "id": "604b61b6aad5fab0f3c0d40d" }, "tripDate": "2021-03-27T22:00:00.000Z", "noOfSets": 7, "transportNotes": "some transportNotes" }, "bookingStatus": "active", "_id": "605dc47ed2ed656bce892182", "salesPerson": "noor smay", "marketSegment": { "_id": "604b60796d049aafef1d3b0a", "marketSegment": "Faceboook", "__v": 0, "id": "604b60796d049aafef1d3b0a" }, "enteredBy": { "role": "admin", "_id": "604d1b9767fa82ccffc29acc", "isAdmin": false, "name": "ahmed magdy", "email": "ahmedmagdy#test.com", "password": "$2a$10$eoYyVF1TTTPQ7pWcCDLVQuvalw8g82yvzzmgD7fvQDH8mCZ4QE30S", "createdAt": "2021-03-13T20:07:51.428Z", "updatedAt": "2021-03-13T20:07:51.428Z", "__v": 0 }, "resDate": "2021-03-26T11:24:46.644Z", "__v": 0, "id": "605dc47ed2ed656bce892182" }
https://docs.mongodb.com/manual/tutorial/update-documents/ updateOne to update 1 record updateMany for multiple records await db.collection('inventory').updateOne({ }, // query { $set: { 'customerAccount.payStatus': 'New Value' } // update value } ); Demo - https://mongoplayground.net/p/iO4I4zVRnOP Mongo query db.collection.update({},{ $set: { "customerAccount.payStatus": "New Value" } })