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

隐身守侯 提交于 2020-01-24 15:54:25

问题


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.

回答1:


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




回答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".



来源:https://stackoverflow.com/questions/50359806/sailsjs-best-way-to-create-and-manage-indexes-on-sails-mongo-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!