Skip to content

Instantly share code, notes, and snippets.

@drmikecrowe
Last active July 25, 2016 07:22
Show Gist options
  • Save drmikecrowe/a966c57c10faceeef7b8 to your computer and use it in GitHub Desktop.
Save drmikecrowe/a966c57c10faceeef7b8 to your computer and use it in GitHub Desktop.
Complex indices (and post-create index) of Waterline models
/**
* FILE: api/hooks/reindex-db.js
*
* Created by mcrowe on 1/28/15.
*
* Insures indices recreated if needed, and allows complex indicies to be specified in the model as well. Example:
*
module.exports = {
schema : true,
version : "1.3",
attributes: {
...
nextCheckDateMax: { type: 'DATE', index: true },
currentSequenceNumber: { type: 'INTEGER' },
enabled: { type: 'BOOLEAN', defaultsTo: true }
},
compoundIndices: {
ci_1: { nextCheckDateMax: 1, currentSequenceNumber: 1 }
}
}
*/
var _ = require('lodash');
function ensureIndexCreated(model, collection) {
var promises = [];
_.each(model.attributes, function(params, index) {
if ( _.has(params,'index') ) {
collection.ensureIndex(index, {background: true}, function(err) {
if ( err ) {
console.log('Error re-indexing collection', err);
}
});
}
});
_.each(model.compoundIndices, function(index) {
collection.ensureIndex(index, {background: true}, function(err) {
if ( err ) {
console.log('Error re-indexing collection', err);
}
});
});
return [];
}
module.exports = function hook(sails) {
return {
/**
* Private hook method to do actual database data operations.
*
* @param {Function} next Callback function to call after all is done
*/
indexDatabase: function indexDatabase(next) {
_.each(sails.models, function(model) {
model.native(function(err, collection) { ensureIndexCreated(model, collection); });
});
console.log("Indices rebuild");
next();
},
/**
* Method that runs automatically when the hook initializes itself.
*
* @param {Function} next Callback function to call after all is done
*/
initialize: function initialize(next) {
var hook = this;
// Wait for sails orm hook to be loaded
sails.after('hook:orm:loaded', function onAfter() {
hook.indexDatabase(next);
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment