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

标签 node.js mongodb mongoose

我有以下更新查询:

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/

相关文章:

javascript - peerjs webrtc调用响应

javascript - 引用错误: barChartHelper is not defined?

mongodb - 使用 mgo 更新插入到分片 MongoDB 错误 "full shard key must be in update object for collection:..."

mongodb - 使用索引在 Mongoose 中设置数组元素的值

node.js - 如何在 sailsJs 中使用 mongoDB 仅在数组中获取 _id 字段

node.js - MongoDB 设置数据库脚本(基于 NodeJS 的项目)

node.js - HTTP 400 : Bad Request error in ADFS HTTPS Request

mysql - Eclipse Che 中的 MySQL 运行时拒绝连接

node.js - 使用MDB排查NodeJS内存泄漏,umem未加载到地址空间

node.js - Mongoose - 使用 findoneandupdate 和 $push 添加或更新子文档(当 upsert 为 true 时)