Reputation: 399
I have the following aggregation stage that I'd like to add to my pipeline, but it keeps failing. When I use the MongoDB Compass Aggregation GUI, everything works as it should. I even exported that pipeline from the GUI and am using It the same way In my project but I keep getting this error:
MongoServerError: A pipeline stage specification object must contain exactly one field.
I even tried to hard-coded a productId in the $match
value (the same way I did in the GUI), but still nothing.
What am I doing wrong here?
Aggregation stage:
const formatIncludedInBomStage = ({ includedInBom }) => {
const includedInBomStage = {
$unwind: {
path: '$finale.bomItems',
},
$match: {
'finale.bomItems.productId': includedInBom,
},
}
return includedInBomStage
}
Upvotes: 0
Views: 709
Reputation: 399
Solution:
const formatIncludedInBomStage = ({ includedInBom }) => {
const filters = {}
if (includedInBom) {
const unwindStage = {
$unwind: {
path: '$finale.bomItems',
},
}
const matchStage = {
$match: {
'finale.bomItems.productId': includedInBom,
...filters,
},
}
const bomStages = [unwindStage, matchStage]
return bomStages
} else return []
}
const includedInBomStage = formatIncludedInBomStage({
includedInBom,
})
const cursor = products.aggregate([stage1,stage2,...includedInBomStage])
Upvotes: 0
Reputation: 29109
Pipeline stages are an array, you are using multiple object properties instead. unwind
should be one stage object in the array, and match
another object in the array.
const stages = [
{
$unwind: {
path: '$finale.bomItems',
},
{
$match: {
'finale.bomItems.productId': includedInBom,
}
}
]
Upvotes: 1