gpt4 book ai didi

node.js - $addToSet 与子文档数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:14 27 4
gpt4 key购买 nike

我有以下更新查询:

var where = 'answers.round_' + ans.round + '_' + ans.iteration

Game.findByIdAndUpdate(gameId, {
$addToSet: {
where: ans
}
}, function(err, model) {
if (err)
throw err
console.log('after game update with answer ' + JSON.stringify(model))
callback()
})

数据库结构如下所示:

 "_id: ObjectId("5304bc1dcf36941e3adcd3fd"),
"answers" : {
"round_1_1" : [],
...
}

问题是 ans 对象没有被插入 "round_1_1" 数组(不是我检查它不是 null)。回调中的模型是我想要更新的模型,只是更新没有发生。

我的问题类似于 this ,就像点符号不起作用(即使在控制台上输出 answers.round_1_1

最佳答案

您确实要将其插入不存在的 where 数组中。因为您的模型中没有这样的字段,所以 Monggose newer 将其发送到 MongoDB。

问题在于您如何构建查询。尝试以下代码:

var query = {$addToSet: {}}
, where = 'answers.round_' + ans.round + '_' + ans.iteration;

query.$addToSet[where] = ans;

Game.findByIdAndUpdate(gameId, query, function(err, model) {
// Your callback function
})

关于node.js - $addToSet 与子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884361/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com