0

I am trying to update the floor_num value from 1 to 9000 in an object in a nested array, in Mongoose:

thingSchema.findById(thingID, function(err, lm) {
  if (!lm){
    console.log(err);
  }
  else {
      lm.update({'style.maps.localMapArray.map_marker_viewID': req.body.map_marker_viewID}, 
      {'$set': {
        'style.maps.localMapArray.$.floor_num': 9000,
      }
      }, function(err) {
        //update success
    });
  }
}); 

But I'm getting this Mongo error:

MongoError: cannot use the part 
   (localMapArray of style.maps.localMapArray.map_marker_viewID) to traverse
   the element ({localMapArray: [ { map_marker_viewID: "acympqswmkui", 
   floor_num: 1 } ]} code: 16837

My schema:

   var thingSchema = new Schema({
        style: {
            maps: {
                localMapArray: [{
                   map_marker_viewID : String,
                   floor_num : Number
                }],
            }
        }
   }); 
2
  • Your code should work fine. You would get the error only if you do not use the $(positional operator.) to update. Commented Feb 20, 2015 at 5:54
  • I agree. The update is fine. Can you double check what error you get, if any? Commented Feb 20, 2015 at 7:33

1 Answer 1

2

Here is my noob way of solving such kind of problems. I am also new to MongoDB and Mongoose.

thingSchema.findById(thingID, function(err, lm) {
    if (err)
        console.log(err);

    var localMaps = lm.style.maps.localMapArray;

    for (var i = 0; i < localMaps.length; i++) {
        if (lm.style.maps.localMapArray[i].map_marker_viewId == req.body.map_marker_viewID) {
            lm.style.maps.localMapArray[i].floor_num = 9000;
        }
    }

    lm.save();
});

I wish somewhere here can give better example with Mongoose. Hope it will help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.