Hi everyone! I need help with writing an aggregation query.
Items collection:
{
_id,
supplierId: { type: Schema.Types.ObjectId, ref: 'Supplier', required: true}
UOMs: [
{
uomCode: { type: Schema.Types.ObjectId, ref: 'UOM', required: true },
packSize: { type: Number, required: true },
//other fields
}
// other fields
],
}
UOM collection:
{
_id: UOM_id,
isActual: { type: Boolean, required: true },
width: { type: Number }
//other fields
}
What I intend to do:
I receive a query with supplierId in a header and a queryCode as a query parameter, and filter it using $match by supplierId. Then I want to populate uomCode field in every object in UOMs array from UOM collection, $unwind the items based on UOMs array and filter the result: select only unwound items with isActual: true and UOM_id === queryCode. I hope this is possible.
My current query looks as this:
const aggregateArray = [
{
$match: itemQuery
},
{
$unwind: {
path: '$UOMs'
}
},
{
$lookup: {
from: 'inv_uoms',
localField: 'UOMs.uomCode',
foreignField: '_id',
let: { id: '$UOMs._id' },
pipeline: [
{
$match: {
$expr: {
$and: [ $eq: { ['$id', queryCode] }, $eq: { ['$isActual', true] } ]
}
}
}
],
as: 'UOMs.uomCode'
}
},
{
$project: {
supplierId: 1,
UOMs: 1
//other fields
}
}
];
const items = await Item.aggregate(aggregateArray);
Currently I receive an array of items with UOMs as an array containing one populated object but uomCode is an EMPTY array. What am I doing wrong?
Thanks for your help!