Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a object in mongodb via mongoose?

Tags:

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?

like image 409
codeofnode Avatar asked Sep 26 '13 07:09

codeofnode


People also ask

How do I update my Mongoose?

The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.

How does Mongoose update work?

When using Mongoose, it is very likely that you will want to update a document. One good method to use is the update() method. It matches a document based on the filter specified, and then makes the update based on the update supplied as well.


1 Answers

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);
like image 120
JohnnyHK Avatar answered Sep 25 '22 14:09

JohnnyHK