【问题标题】:Saving in a nested array MongoDB保存在嵌套数组 MongoDB 中
【发布时间】:2016-10-31 07:00:33
【问题描述】:

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

-使用猫鼬-

var postSchema = new mongoose.Schema({
  raidName: String,
  raidDate: String,
  raidTime: String,
  raidFaction: String,
  whosGoing: { type: Array, "default": []}
});


var realmSchema = new mongoose.Schema({
  realmName: String,
  posts: [postSchema]
});

下面是我的数据库的样子

{
    "_id": {
        "$oid": "581447f5fb4fab06dcbf10a6"
    },
    "realmName": "Cho'gall",
    "posts": [
        {
            "raidName": "wailing cavs",
            "raidDate": "Sat Oct 29 2016",
            "raidFaction": "Horde",
            "raidTime": "1:01 AM",
            "_id": {
                "$oid": "58144806fb4fab06dcbf10a7"
            },
            "whosGoing": [
                {
                    "role": "DPS",
                    "gender": "Male",
                    "race": "Orc",
                    "classImg": "../images/class_photos/monk.png",
                    "class": "Monk",
                    "level": 90,
                    "name": "Monnky"
                }
            ]
        }
    ],
    "__v": 1
}

我可以创建新帖子没问题, 但是我不知道如何将更多对象添加到“whosGoing”数组中...... 下面是我在做什么..

  var Realms = mongoose.model('realms');

  Realms.findOne({realmName: realm}, function (err, realm) {
    realm.posts.id(postId).whosGoing.push(thisChar); //pushing it here no problem
    console.log(realm.posts.id(postId).whosGoing); //when i log it here both objects are in the array just fine
    console.log(realm); //but when i log the realm here, the item i just pushed is not in there, so of course if I realm.save() it wouldnt take effect...
    realm.save();
  })

有人能解释一下为什么会这样吗..

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    有一个类似的问题here

    但基本上你可以使用 &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);
      }
    }
    

    【讨论】:

      【解决方案2】:

      使用$push 运算符:

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

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

      【讨论】:

        猜你喜欢
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 1970-01-01
        • 2017-07-26
        • 2021-12-03
        • 2021-06-27
        相关资源
        最近更新 更多