Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing schemas in mongoDB/mongoose

I am getting started with mongoDB and mongoose. I was wondering how people manage evolving schemas. For example if i started with a schema like this:

user_ID : 123,
user_firstName : 'bob',
user_lastName : 'smith'

And evolved it to something like this:

user_ID: 123,
user_name: [first:'bob', last:'smith']

How could I update or manage old records that were established using the old schema design?

like image 317
wilsonpage Avatar asked Sep 26 '11 08:09

wilsonpage


People also ask

What is schema in Mongoose?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

Is schema necessary for Mongoose?

Mongoose models and their schemas allow you to perform validation on the fields you expect or are required. But if you stop there then you've just got the equivalent of a relational schema.


Video Answer


1 Answers

One approach to migrating document schemas involving simple data transformations would be to use $exists to find documents that are missing the new fields and migrate them.

For example, transforming firstName and lastName into a new user_name field:

db.mycollection.find( { user_name : { $exists : false } } ).forEach(
    function (doc) {
        doc.user_name = {'first': doc.user_firstName, 'last': doc.user_lastName};

        // Remove old properties
        delete doc.user_firstName;
        delete doc.user_lastName;

        // Save the updated document
        db.mycollection.save(doc);
    }
)

For more complex migrations some tools that could be helpful are:

  • schema.js or variety for analyzing the current schema of a collection
  • JSV: JSON Schema Validator for validating documents
like image 146
Stennie Avatar answered Sep 18 '22 14:09

Stennie