Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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);
- });
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement