【发布时间】:2019-12-10 01:26:20
【问题描述】:
我正在尝试更新具有嵌套文档的 MongoDB 集合中的字段。我必须增加一定的价值。更新查询工作得很好,但我需要将它嵌套在另一个查询中,在那里我得到当前值,所以我可以增加它。
当我使用错误的find() 方法时,嵌套工作得很好。我意识到我必须使用aggregate()。我无法让它工作,该方法由于某种原因返回未定义。我已经在 shell 中尝试了相同的聚合查询并且它可以工作,所以它必须对 Node.js 做一些事情
失败的函数:
static addPointsToUser(mainId, userId, pointsToAdd) {
const db = getDb();
function getCurrent() {
db.collection('mycoll')
.aggregate([
{ $match: { _id: mainId } },
{ $unwind: '$userPoints' },
{ $match: { 'userPoints._id:': userId } },
{ $group: { _id: 'userPoints._id', userPoints: { $push: '$userPoints.points' } } }
])
}
function updateNew(newPoints) {
db.collection('mycoll')
.updateOne(
{ _id: mainId },
{ $set: { "userPoints.$[elem].points": newPoints } },
{
multi: true,
arrayFilters: [{ "elem._id": userId }]
}
)
}
return getCurrent()
.then(result => {
console.log(result);
const newPoints = result.userPoints[0];
return updateNew(newPoints)
.then(result => {
console.log(result);
return result;
})
})
}
文档如下所示:
{
"_id": ObjectId("5d4048f56a895612acabe0a9"),
// Some other fields
"userPoints": [
{ "_id": "manualID1", "points": 80 },
{ "_id": "manualID2", "points": 90 }
]
}
预期的汇总结果:
{ "_id" : "manualID1", "userPoints" : [ 90 ] }
Mongo shell 给出了上面看到的结果。
实际结果: TypeError: 无法读取未定义的属性 'then'
如果我记录它打印的聚合结果和空数组 ( [] )。
【问题讨论】:
标签: javascript node.js mongodb