21

I have mongoose schema as:

var Organization = new Schema({
  name: String,
  address: {
    street : String,
    city: String
  }
}, { collection: 'organization' });

How do I update only street part of address for an organization via mongoose?

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
codeofnode
  • 18,169
  • 29
  • 85
  • 142
  • i had found only about the subdocument array not about the simple object subdocument. In my case, i do not have subdocument array. – codeofnode Sep 26 '13 at 07:09

3 Answers3

29

I can't find any docs that cover this simple case so I can see why you're having trouble. But it's as simple as using a $set with a key that uses dot notation to reference the embedded field:

OrganizationModel.update(
  {name: 'Koka'}, 
  {$set: {'address.street': 'new street name'}}, 
  callback);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • I believe the preferred mechanism for updating via mongoose, is to use the mongoose wrapper, as shown here: http://stackoverflow.com/questions/7267102/how-do-i-update-upsert-a-document-in-mongoose – Michael Merchant Apr 02 '15 at 11:35
6

Now you can update directly .

OrganizationModel.update(
 {name: 'Koka'}, 
 {'address.street': 'new street name'}, 
 callback);
Prayag k
  • 647
  • 9
  • 23
2

Using Document set also, specified properties can be updated. With this approach, we can use "save" which validates the data also.

  doc.set({
        path  : value
      , path2 : {
           path  : value
        }
    }

Example: Update Product schema using Document set and save.

// Update the product
let productToUpdate = await Product.findById(req.params.id);

if (!productToUpdate) {
  throw new NotFoundError();
}

productToUpdate.set({title:"New Title"});
await productToUpdate.save();

Note - This can be used to update the multiple and nested properties also.

mohit uprim
  • 5,226
  • 2
  • 24
  • 28