I'm trying to create an e commerce web site using react, node and mongodb. I created the order schema which comports the cmdRef(string), theClient(Id of the user) and an array of Products(with ProductId and qty) like the code below:
Orderchema=new mongoose.Schema({
CmdRef:String,
Client:{type: mongoose.Schema.Types.ObjectId,
ref: 'User'},
TotalProducts:[{ProductId:{type: mongoose.Schema.Types.ObjectId,
ref: 'Product'},Quantity:Number}],
and now I'm trying to create the route to get all the Orders
CommandRouter.get('/AllCommands',async(req,res)=>{
try {
const cmd= await Command.find({}).populate({path: 'Client', select: 'firstName lastName'}).populate({path:'TotalProducts'})
//
res.json(cmd)
} catch(error)
{
return res.status(500).send({message : "error get orders"})
}
})
Here I found a problem while populating the products Id in the table it populates the client Id and returns all information about the User but fail with the product table this is the full response using PostMan
Have any of you any Idea about how to populate the productId in the TotalProducts table?
Total products is not an ObjectId. You should be populating ProductId instead.
This should work.
const cmd = await Command
.find({})
.populate([
{
path: 'Client',
select: 'firstName lastName'
},
{
path: 'TotalProducts'
populate: 'ProductId'
}
]);