How do I $push a value to an array within an embedded document in MongoDB using Mongoose?

71 views
Skip to first unread message

Jay Tolla

unread,
Oct 24, 2014, 9:35:14 AM10/24/14
to mongod...@googlegroups.com

It seems this may be an open issue with MongoDB, https://jira.mongodb.org/browse/SERVER-831, but I'm not sure if there's actually a solution and I'm just thinking about and researching things in the wrong way.

Here is a subset of my schema:

var myModel = new mongoose.Schema({

  arrayA: [{
    subArrayA: [{
        fieldA: String
    }],
    subArrayB: [{
        fieldB: String
    }]
  }],

});

I want to update subArrayA by pushing a value into it. I've tried doing this in various ways with no success. This is the simplest attempt:

myModel.findByIdAndUpdate(req.mymodel.arrayA.id(req.params.id), {
        $push: {
            subArrayA: {
                fieldA: valA
            }
        }
}, function(err) {
     // some stuff
});
I've also tried using "dot notation" in the following way with no success:
myModel.findByIdAndUpdate(req.mymodel.arrayA.id(req.params.id), {
        $push: {
            arrayA.subArrayA: {
                fieldA: valA
            }
        }
}, function(err) {
     // some stuff
});
Everything works fine when pushing directly to arrayA. For example, the code below executes the way I'd hope - by pushing a value into arrayA:
myModel.findByIdAndUpdate(req.mymodel.id, {
    $push: {
        arrayA: {
            fieldA: valA
        }
    }
}, function(err) {
     // some stuff
});
Any help would be much appreciated.

Sabari Sri

unread,
Oct 25, 2014, 8:17:09 AM10/25/14
to mongod...@googlegroups.com
Hi,

Try the below option.

myModel.find({_id : yourModelId})
      .exec(function(err,modelObj){
     for(var i=0;i<modelObj.arrayA.length;i++){
       if(modelObj.arrayA[i].id.toString()==req.param.id.toString()){
          modelObj.arrayA[i].subArrayA('your_string');
       }
     }
});
<code style="font-family: 
...
Reply all
Reply to author
Forward
0 new messages