$ addToSet与子文档的数组

我有以下更新查询:

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 )。 callback模型是我想要更新的模型,只是更新不会发生。

我的问题是类似于这个 ,就像点符号不工作(即使在控制台上它输出answers.round_1_1

你正在把它推到不存在的where 。 由于模型中没有这样的字段,所以Monggose将它发送到MongoDB。

问题是你如何构build你的查询。 试试下面的代码:

 var query = {$addToSet: {}} , where = 'answers.round_' + ans.round + '_' + ans.iteration; query.$addToSet[where] = ans; Game.findByIdAndUpdate(gameId, query, function(err, model) { // Your callback function })