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

2

5

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.
Shih answered 15/5, 2018 at 22:5 Comment(1)
npmjs.com/package/sails-hook-mongo-indexSomeway
W
4

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

Warp answered 25/2, 2019 at 23:32 Comment(2)
Thanks Dimas! Thats great. I've also created a script that deletes all indexes from all collections, in case of index migration.Shih
or simply: npm i --save sails-hook-mongo-index it will ensure indexes automatically.Someway
E
2

In development mode you can specify custom indexes in the model within Sails, or it will remove them when lifting the server and performing migration.

My (preferred) alternative approach is to manage all indexes on my own within the DB. In order to do so, you have to change the "migrate" attribute from "alter" to "safe" in models.js config file.

Note that in production mode "migrate" attribute is always set to "safe".

Explication answered 28/6, 2018 at 16:57 Comment(1)
Do you use any tool to create the indexes and models. Or you aways go index by index on hand?Shih

© 2022 - 2024 — McMap. All rights reserved.