如何在猫鼬中更新对象内部数组中的对象? [英] How to update object inside array inside object in Mongoose?

查看:67
本文介绍了如何在猫鼬中更新对象内部数组中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MongoDB的新手,我有一个组织的MongoDB集合.并且有classes (object)的数组.我目前正将Node.js与Mongoose结合使用,以更新班级内部教师的count.当前收藏如下.

I am new to MongoDB and I have a MongoDB collection of an organization. And there are array of classes (object). I am currently using Node.js with Mongoose to update the count of teachers inside classes. The current collection is as below.

//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,
            }
        ]
    }
]
}

每当我通过猫鼬更新组织时,我都希望增加教师人数.我这样写.

I want to increase the count of a teacher whenever I update the organization via Mongoose. I wrote like this.

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

请帮助我查询和增加教师人数.

Please help me how to query and increase the count of a teacher.

推荐答案

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

You can just retrieve it manually and manipulate at javascript level and then you can save it to model.

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();

});

这篇关于如何在猫鼬中更新对象内部数组中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆