Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sailsjs. Best way to create (and manage) indexes on sails-mongo (mongodb)

I was using sailsjs 0.12. It supported index attributes on models, also i was using npm package Sails-hooks-mongoat to create inverse indexes and so.

It wasn't ideal, but it worked. Right now they dropped the index attribute and mongoat is currently unsafe and pending updates to work on Sails.js 1.0.

I would like to know the best approach to:

  • Create Indexes on new deployments.
  • Migrate (ensure?) indexes on deployment updates.
like image 650
Gustavo Garcia Avatar asked May 15 '18 22:05

Gustavo Garcia


1 Answers

Since you are not allowed to run 'migrate: alter' in production (even if you try), one option is to create those index in bootstrap file ('config/bootstrap.js').

Imagine you have an User model like this:

var User = {
  attributes: {
    email     : { type: 'string', unique: true, required: true },
    username  : { type: 'string', unique: true, required: true },
    pin: { type: 'string'}
  }
};

module.exports = User;

Then you can manually create the missing indexes like this in bootstrap file:

module.exports.bootstrap = async function(done) {
  console.log("Loading bootstrap...")

  if (process.env.NODE_ENV === 'test') {

  }

  if (process.env.NODE_ENV === 'production') {
      console.log("CREATING DATABASE INDEX BY HAND")

      // USER MODEL
      var db = User.getDatastore().manager;
      await db.collection(User.tableName).createIndex( { email: 1 }, {unique: true} );
      await db.collection(User.tableName).createIndex( { username: 1 }, {unique: true} );
      // PANDA MODEL
      // db = Panda.getDatastore().manager;
      // await db.collection(Panda.tableName).createIndex( { name: 1 }, {unique: true} );
  }

  // await initializeDatabase() // custom DB initialization...

  return done();
};

The index are created only once, subsequent runs will not recreate those indexes. The ensureIndex was an alias to createIndex function and it has been deprecated.

References:

Waterline manager reference

MongoDB create index reference

like image 84
Dimas Crocco Avatar answered Oct 04 '22 02:10

Dimas Crocco