Search code examples
node.jsmongoosenosqlsql-updatemongoose-schema

How to update old documents after adding new fields to the schema?


let's say I have a user schema that looks like this:

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true
    }
});

And then some people signed up in the website and user documents were created.

Then at some point in the future I added these additional fields to the user schema:


    joinedAt: {
        type: Data,
        default: Date.now,
    },
    about: {
        type: String,
        required: true,
    }

What should I do to update old data? I come from django and in django I just run python3 manage.py makemigrations and it will apply the changes to all existing data if it wasn't required or had a default value (Like joinedAt in this case).

But if it didn't (Like about field in this case) then it will ask me what should be the value for existing fields.

How is it done in Node.js?


Solution

  • Just write a MongoDb update query like this:

    let about = "Whatever you want";
    
    db.users.updateMany(
        {
            joinedAt: { $exists: false },
            about: { $exists: false },
        },
        {
            $set: {
                joinedAt: new Date(),
                about: about
            }
        }
    );
    

    OR

    If you want a Node.js script then:

    STEP 1: Create a file user_migration.js:

    const MongoClient = require('mongodb').MongoClient;
    const DB_URI = "mongodb://localhost:27017/myDB";
    
    const options = {
      useNewUrlParser: true
    };
    
    MongoClient.connect(DB_URI, options, (err, client) => {
      if (err) {
        console.log("ERROR: Failed to connect to database.");
        console.log(err);
        return;
      }
    
      let dbName = DB_URI.split("/", -1).pop();
      let db = client.db(dbName);
    
      console.log(`Connected to ${dbName} database successfully.`);
    
      let about = "Whatever you want";
      db
        .collection('users')
        .updateMany(
          {
            joinedAt: { $exists: false },
            about: { $exists: false },
          },
          {
            $set: {
              joinedAt: new Date(),
              about: about
            }
          }
        )
        .then(res => {
          // console.log(res);
          console.log(`${res.result.nModified} documents updated successfully.`);
          console.log("Database connection closed.");
          client.close();
        })
        .catch(err => {
          console.log(JSON.stringify(err));
          console.log("Database connection closed.");
          client.close();
        });
    });
    

    STEP 2: Run the file from the terminal:

    node C:path\to\your\source_code\user_migration.js