Khay
Khay

Reputation: 1570

How to update object inside array inside object in Mongoose?

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.

Upvotes: 0

Views: 888

Answers (1)

Naing Lin Aung
Naing Lin Aung

Reputation: 3430

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

});

Upvotes: 1

Related Questions