javascript - Node.js:无法读取未定义的属性“then”(嵌套查询)
问题描述
我正在尝试更新具有嵌套文档的 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: Cannot read property 'then' of undefined
如果我记录它打印的聚合结果和空数组( [] )。
解决方案
你的方法getCurrent
并updateNew
没有返回任何东西。这意味着您正在使用未定义.then()
的内容,如您的错误消息所述。
之前添加一个return
语句db.collection('mycoll')
应该可以帮助你。
推荐阅读
- laravel - 在 Laravel 中使用 users 表中的电子邮件发送电子邮件
- arrays - 用字典数组填充表格视图并按部分分隔
- html - 通过 css 从其他字体获取连字
- flutter - 图像未在 Flutter 中显示
- java - 如何测试我的脚本 sh 是否仍在由 JAVA 运行
- python - 带有软删除的 SQLAlchemy 关联表
- django - Django all-auth:如何通过 Google 禁用自动登录
- sql-server - SQL查询列出特定数据库/服务器中的所有表+列?
- c++ - g++ 的分段错误(在 NaN 上使用两次 to_string 时)
- c# - 有没有办法减少加载 cshtml 视图的时间?