I am using mongoose and MongoDB for my Node.js project. I have basic schemas, and since the project is new I am updating some properties in the schemas. But, when I update a schema's some property (this may adding or removing property), the change is not updated to old documents that exist in the collection. How can I update older documents when changing a schema's properties.
CodePudding user response:
Let's say I created a new property on a UserSchema. The new property is called "test", it is of type String, and it is not required. This new property I added is a non-breaking change. None of my existing documents have changed any yet. I have yet to populate them.
Open the MongoSH (Mongo Shell).
Navigate to my database:
show dbs;
use <db>
;
Update all documents with an unpopulated test field using db.collection.updateMany():
db.collection.updateMany( {test: null}, { $set: { test: “123” } })
Similar Question found here: Add new field to every document in a MongoDB collection