Migration in MongoDB

Migration in MongoDB

Β·

2 min read

console.log("Hello Hashnode FamπŸ’–")

I hope you are doing well ! 😊

Sometime there arises a need where you have to add a new field with default values to your existing schema after creating the database at the initial level. But adding it to your schema file will only reflect it in the new created data.

So, the question arises what should be done so that the newly added field sets its default data into the existing data. To tackle this type of situation, migration is the first thing that comes to your mind isn't it ? But there is no inbuilt provision for running migrations in MongoDB.

Today we are going to discuss about a package named mongo-migrate available in npm (Node Package Manager) which can help you in resolving the above situation.

Installation and Setup

  1. Install the package by running

    npm install -g migrate-mongo

    ( -g flag is for global installation and is optional ).

  2. Run the below command to initialize the migration.

    migrate-mongo init

    This will create 2 changes into your directory structure:

    • migrate-mongo-config.js (configuration file)
    • migrations (Folder)
  3. Open your migrate-mongo-config.js file and make the following changes.

  // In this file you can configure migrate-mongo

   module.exports = {
     mongodb:  {
       url:  "{your_database_connection_url}",

       databaseName:  "{your_database_name}",

       options:  {
         useNewUrlParser:  true  // removes a deprecation warning when connecting
       }

     },

     migrationsDir:  "migrations",

     changelogCollectionName:  "changelog",

     migrationFileExtension:  ".js",

     useFileHash:  false,

     moduleSystem:  "commonjs"
   };

Note: moduleSystem can be configured as:

  • CommonJs (commonjs)

    This module system is built into Node.js. It was one of the standardized module to be used before the introduction of esm.

  • ESM (esm)

    ES module is the standard for JavaScript but it lacks to support the node versions lower than 9.

Creating a Migration

  1. Create the migration using the below command.

    migrate-mongo create name_of_your_migration

    (e.g :- migrate-mongo create add_column_viewers)

  2. Go to your newly created migration file inside the migrations folder and write the up and down migration.

module.exports = {
  up(db){
    return db.collection('your_collection_name').updateMany(
      {
        where_condition
      },
      {
        $set:{
          your_column_name:value
        }
      });
  },
  down(db){
     return db.collection('your_collection_name').updateMany(
      {
        where_condition
      },
      {
        $unset:{
          your_column_name:null
        }
      });
  }
}

Note: Don’t forget to write the code in the down migration. It is a mandatory as well as a good practice to write the exactly opposite operation in the down method as compared to the up method.

Executing a Migration

  1. Run the up migration using

    migrate-mongo up

  2. Run the down migration using

    migrate-mongo down

I hope this was an useful read! Comment your views, feedbacks and something you think this article must contain.

Thanks for reading! 😊

Β