保存在嵌套数组MongoDB中

时间:2016-10-29 18:29:20

标签: mongodb express mongoose

我不明白为什么mongoDB会这样做,所以也许有人可以解释......下面是我的模式和代码,

- 使用猫鼬 -

TaskCompletionSource<bool>

下面是我的数据库的外观

TaskCompletionSource<object>

我能够创建新帖子没问题, 但是,我不知道如何在&#39; whosGoing&#39;阵列.... 下面就是我在做什么..

link_to "X", remove_item_path(id: item.id), method: :delete

有人可以解释为什么会发生这种情况。

2 个答案:

答案 0 :(得分:1)

有一个类似的问题here

但基本上你可以使用&amp; elementMatch在数组中找到欲望的帖子,并使用位置$运算符来识别查询中匹配的帖子。例如:

var query = {
  "realmName": realm,
  "posts": { 
    $elemMatch: { 
      "_id": postId
    } 
  }
}

var setField = {
  $addToSet: {
    "posts.$.whosGoing": thisChar
  }
}

Realms.update(query, setField, function(err, results){
  if (err){console.log(err)}
  else {
   console.log(results);
  }
}

答案 1 :(得分:0)

使用$push运算符:

Realms.update({ realmName: realm }, { $push: { whosGoing: thisChar } }, ...)

还有$pull运算符用于从数组中删除值。