Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mongoose, update values in array of objects

Mongoose, update values in array of objects

Problem

Is there a way to update values in an object?

{
  _id: 1,
  name: 'John Smith',
  items: [{
     id: 1,
     name: 'item 1',
     value: 'one'
  },{
     id: 2,
     name: 'item 2',
     value: 'two'
  }]
}

Lets say I want to update the name and value items for item where id = 2;

I have tried the following w/ mongoose:

var update = {name: 'updated item2', value: 'two updated'};
Person.update({'items.id': 2}, {'$set':  {'items.$': update}}, function(err) { ...

Problem with this approach is that it updates/sets the entire object, therefore in this case I lose the id field.

Is there a better way in mongoose to set certain values in an array but leave other values alone?

I have also queried for just the Person:

Person.find({...}, function(err, person) {
  person.items ..... // I might be able to search through all the items here and find item with id 2 then update the values I want and call person.save().
});
Problem courtesy of: lostintranslation

Solution

You're close; you should use dot notation in your $set to do that:

Person.update({'items.id': 2}, {'$set': {
    'items.$.name': 'updated item2',
    'items.$.value': 'two updated'
}}, function(err) { ...
Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Mongoose, update values in array of objects

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×