Last active
August 29, 2015 14:06
-
-
Save klclee/54f7e96f3c359a824c59 to your computer and use it in GitHub Desktop.
mongoose connection util (with model look up and drop collections)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var mongoose = require('mongoose'); | |
var config = require('../config/database.json'); | |
var database = null; | |
var RSVP = require('rsvp'); | |
module.exports = { | |
init: function(envSt) { | |
if (database == null) { | |
var env = config[envSt]; | |
var rsvp = new RSVP.Promise(function(resolve, reject){ | |
mongoose.connection.on('open', function(){ | |
console.log("connecting to " + env.host + " at " + env.port + " on " + env.databaseName + " with " + JSON.stringify(env.serverOptions)); | |
resolve(); | |
}); | |
mongoose.connection.on('error', function(err){ | |
reject(err); | |
}); | |
}); | |
database = mongoose.connect('mongodb://' + env.host + ':' + env.port + '/' + env.databaseName, env.serverOptions); | |
return rsvp; | |
} | |
}, | |
model: function(modelName) { | |
// return mongoose.model(model_name, eval("" + model_name + "_model")); | |
var requireSt = './models/' + modelName; | |
return mongoose.model(modelName, require(requireSt)); | |
}, | |
drop: function(){ | |
var currentEnv = require('./currentEnv'); | |
var dropCollections = []; | |
var rsvp = null; | |
if(currentEnv.get() !== 'production'){ | |
rsvp = new RSVP.Promise(function(resolve, reject){ | |
database.connection.db.collections(function (err, collections) { | |
var todo = collections.length; | |
if(todo === 0){ | |
resolve(); | |
} | |
collections.forEach(function(collection){ | |
if(!collection.collectionName.match(/^system\./)){ | |
collection.remove({},{safe: true},function(){ | |
console.log('removing collection', collection.collectionName); | |
if (--todo === 0) { | |
resolve(); | |
} | |
}); | |
}else{ | |
if (--todo === 0) { | |
resolve(); | |
} | |
} | |
}); | |
}); | |
}); | |
} | |
return rsvp; | |
}, | |
close: function() { | |
var rsvp = new RSVP.Promise(function(resolve, reject){ | |
database.connection.on('close', function(){ | |
resolve(); | |
}); | |
}); | |
database.connection.close(); | |
return rsvp; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment