我有下面的聚合阶段,我想添加到我的管道中,但是它一直失败。当我使用MongoDB Compass聚合GUI时,一切都按其应有的方式工作。我甚至从GUI导出了这个管道,并在我的项目中以同样的方式使用它,但是我一直收到这样的错误:MongoServerError: A pipeline stage specification object must contain exactly one field.
我甚至试图在productId值中硬编码一个$match
(就像在GUI中那样),但仍然没有。
我在这里做错什么了?
集合阶段:
const formatIncludedInBomStage = ({ includedInBom }) => {
const includedInBomStage = {
$unwind: {
path: '$finale.bomItems',
},
$match: {
'finale.bomItems.productId': includedInBom,
},
}
return includedInBomStage
}
发布于 2022-07-18 14:28:12
解决方案:
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])
发布于 2022-07-15 14:24:10
管道阶段是一个数组,而是使用多个对象属性。unwind
应该是数组中的一个阶段对象,而match
应该是数组中的另一个对象。
const stages = [
{
$unwind: {
path: '$finale.bomItems',
},
{
$match: {
'finale.bomItems.productId': includedInBom,
}
}
]
https://stackoverflow.com/questions/72995249
复制相似问题