We're rapidly developing an application that's using Mongoose, and our schema's are changing often. I can't seem to figure out the proper way to update a schema for existing documents, without blowing them away and completely re-recreating them from scratch.
I came across http://mongoosejs.com/docs/api.html#schema_Schema-add, which looks to be right. There's little to no documentation on how to actually implement this, making it very hard for someone who is new to MongoDB.
I simply want to add a new field called enabled. My schema definition is:
var sweepstakesSchema = new Schema({ client_id: { type: Schema.Types.ObjectId, ref: 'Client', index: true }, name: { type: String, default: 'Sweepstakes', }, design: { images: { type: [], default: [] }, elements: { type: [], default: [] } }, enabled: { type: Boolean, default: false }, schedule: { start: { type: Date, default: Date.now }, end: { type: Date, default: Date.now } }, submissions: { type: Number, default: 0 } });
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.
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.
Mongoose Schematype is a configuration for the Mongoose model. Before creating a model, we always need to create a Schema. The SchemaType specifies what type of object is required at the given path. If the object doesn't match, it throws an error.
The $set operator replaces the value of a field with the specified value.
Considering your Mongoose model name as sweepstakesModel
, this code would add enabled
field with boolean value false
to all the pre-existing documents in your collection:
db.sweepstakesModel.find( { enabled : { $exists : false } } ).forEach( function (doc) { doc.enabled = false; db.sweepstakesModel.save(doc); } )
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. In a case like the new enabled
field, it's probably cleanest to write your code so that it treats a missing enabled
field as if it was set to false
so you don't have to touch the existing docs.
As far as the schema change itself, you just update your Schema
definition as you've shown, but changes like new fields with default
values will only affect new documents going forward.
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