如何更新Mongoose中对象内的数组内的对象?

时间:2015-02-11 08:43:29

标签: node.js mongodb mongoose

我是MongoDB的新手,我有一个组织的MongoDB集合。并且有一系列classes (object)。我目前正在使用带有Mongoose的Node.js来更新类中的count教师。目前的收集如下。

//organization
{
"_id" : ObjectId("54db07ab12545794bf7c2d1b"),
"name" : “Stackoverflow”,
"classes" : [ 
    {
        "name" : “Stack 01”,
        "_id" : ObjectId("54db07ab12545794bf7c2d1f"),
        "teachers" : [ 
            {
                "idUser" : "54d1e8fe14a880bea6288eb6",
                "locked" : false,
                "count" : 0,
            }, 
            {
                "idUser" : "54d321cb190c919759b8a8bb",
                "locked" : false,
                "count" : 0,
            }, 
            {
                "idUser" : "54d32147ceaa3a665958b096",
                "locked" : true,
                "count" : 0,
            }
        ]
    }, 
    {
        "name" : “Stack 02“,
        "_id" : ObjectId("54db07ab12545794bf7c2d1c"),
        "teachers" : [ 
            {
                "idUser" : "54d1e8fe14a880bea6288eb6",
                "locked" : false,
                "count" : 0,
            }, 
            {
                "idUser" : "54d32147ceaa3a665958b096",
                "locked" : true,
                "count" : 0,
            }
        ]
    }
]
}

每当我通过Mongoose更新组织时,我都希望增加教师的数量。我是这样写的。

Organization.findOneAndUpdate(
    {_id: "54db07ab12545794bf7c2d1b", 
    "classes._id": "54db07ab12545794bf7c2d1f"},
    {
        $inc: {"classes.$.teacher.$.count": 1}
    },function(err, org){});

请帮我查询和增加老师的数量。

1 个答案:

答案 0 :(得分:1)

您可以手动检索它并在javascript级别进行操作,然后将其保存到模型中。

var query = {_id: "54db07ab12545794bf7c2d1b"}

Organization.findOne(query,function(err, org){

      var classes = org.classes; 
      var index = null;

      for (var i in classes) {
          if (class[i]._id === ObjectID("54db07ab12545794bf7c2d1f")) {
              var index = i;
              break;
          }
      }

      var teachers = org.classes[index].teachers;

      for (i in teachers) {
         if (teachers[i].idUser === '54d1e8fe14a880bea6288eb6' ) {
             teachers[i].count++;
         }    
      }

      org.classes[index].teachers = teachers;
      org.save();

});