Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Add new Schema property and update all current documents

I have at production a NodeJS application running using MongoDB and Mongoose, which inside has a Mongoose Schema like:

var Product = new Schema({
    "name": { type: String, required: true }
  , "description": { type: String }
});

Now, as a new requirement I'm adding a new property to the Schema at my local, like this:

var Product = new Schema({
    "name": { type: String, required: true }
  , "description": { type: String }
  , "isPublic": { type: Boolean, default: true }
});

When I restart my NodeJS process, I was expecting an update to all of my current documents (products), so now every document have a property isPublic which value is true.

What happened is no document has that new property and if I do a someProduct.Save({ isPublic: true }) it gets added.

Question: is there a way to accomplish that?, I know I can do a $set from command line with mongo client, but I want to know if there is a way where Mongoose will add the missing property after the Schema changed on a process restart.

like image 757
pjnovas Avatar asked Oct 15 '14 01:10

pjnovas


People also ask

How can I update multiple documents in Mongoose?

Mongoose | updateMany() Function The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition.

What does $Set do in Mongoose?

Mongoose getters and setters allow you to execute custom logic when getting or setting a property on a Mongoose document. Getters let you transform data in MongoDB into a more user friendly form, and setters let you transform user data before it gets to MongoDB.

Can you change a Mongoose schema?

There's nothing built into Mongoose regarding migrating existing documents to comply with a schema change. You need to do that in your own code, as needed.

What is Upsert in Mongoose?

May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.


1 Answers

What happened is no document has that new property and if I do a someProduct.Save({ isPublic: true }) it gets added.

That's because the mongoose default attribute works just for new documents. There're two workarounds:

  • Write your code to treat documents without the isPublic property as true;
  • Or, as you've mentioned above, set the property manually through mongodb console.
like image 150
Rodrigo Medeiros Avatar answered Nov 09 '22 01:11

Rodrigo Medeiros