I use mongodb + node.js + mongoose.js ORM backend.
Let say I I have some nested array of object without _id field
mongoose.Schema({ nested: [{ _id: false, prop: 'string' }] })
And then I want to ad _id field to all nested objectds, so the mongoose schema would be
mongoose.Schema({ nested: [{ prop: 'string' }] })
Then I should run some script to modify production DB, right? What is the best way to handle such change? Which tool (or approach) is best to use to implement the change?
Collections in MongoDB do not have a fixed schema, or requirement for all documents in a collection to have the same schema. You can definitely add or remove fields, change field types, or update JSON Schema validation without recreating a collection.
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.
A breaking or destructive change includes renaming an existing field or changing a field's data type. For more information, see Update Your Schema. If you need to make a breaking schema change, you have two choices: Terminate sync in the backend and then re-enable it from the start.
One of the significant advantages of schema-less databases is that you don't have to update the entire database with new schema layouts. If some of the documents in the DB don't have particular information, then your code can do the appropriate thing instead, or elect to now do anything with that record.
Another option is to lazily update the documents as required - only when they are looked at again. In this instance, you might elect to have a per-record/document version flag - which initially may not even appear (and thus signify a 'version 0'). Even that is optional though. Instead, your database access code looks for data it requires, and if it does not exist, because it is new information, added after a code update, then it would fill in the results to the best of its ability.
For your example, converting an _id:false
into a standard MongoId
field, when the code is read (or written back after an update), and the _id:false
is currently set, then make the change and write it only when it is absolutely required.
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