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.
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.
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.
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.
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.
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:
isPublic
property as true
;If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With