Hello Every one, I am trying to query order items from the array I have two collections for the query orders and items
- Orders Schema:
{ addedBy: { type: Schema.Types.ObjectId, ref: 'tbl_users', require: true }, name: { type: String, require: true }, mobile: { type: String, require: true }, items: [{ item: { type: Schema.Types.ObjectId, ref: 'tbl_items', require: true }, quantity: { type: Number, require: true } }] }
- Items Schema:
{ name: { type: String, required: true }, weight: { type: Number, required: true }, price: { type: Number, required: true }, }
if I populate items from the orders collection then it returns result in this shape:
for this find query:
await OrdersSchema.find() .populate('items.item');
I get this:
name: abc, mobile: 1234567890, items: [ { name: abc, weight: 500, price: 3.99 }, quantity: 1 }, { name: def, weight: 500, price: 3.99 }, quantity: 2 }, ]
is there any way that I can achieve this with lookup ? the problem occurs is that lookup adds new field item in items array like this
for this query,
await OrdersSchema.aggregate([ { $match: findQuery }, { $lookup: { from: "tbl_items", localField: "items.item", foreignField: "_id", as: "items.item" } }, ]);
I get this:
items: [ item: [{ name: abc, weight: 500, price: 3.99 }, { name: def, weight: 500, price: 3.99 }] ]