mongoose-migrate
mongoose-migrate copied to clipboard
Redis example, but no Mongoose
In the examples folder, it's showing how to do all of this in Redis. Is there a good example how to pull this off in Mongoose?
+1
I'm assuming that within the individual migrations we should already have access to an open mongoose connection, is that correct?
We have an app that makes use of both mongoose and mongodb driver for some migrations, and schema updates, so I got this working easily this way.
I created a dbConnect.js
interface to be required in the migrations.
├── migrations
│ ├── 001-update-user-name-first-last-mongodb.js
│ └── dbConnect.js
in config/migrations.js
var path = require('path');
require('dotenv').load({
path: path.resolve(__dirname,'../.env')
});
module.exports = {
local: {
schema: { 'migration': {} },
modelName: 'Migration',
db: process.env.MONGODB_URL || 'mongodb://localhost/example_com_dev'
}
};
we use .env
to load server specific config
and contents of dbConnect.js
var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var mongodb = null;
mongoose.connect(process.env.MONGODB_URL);
module.exports = {
mongoose: mongoose,
mongodb: MongoClient.connect(process.env.MONGODB_URL) // mongo Driver return a Promise
};
and then in the migrations (this example is using mongodb driver, mongoose will be easier)
var dbConnect = require('./dbConnect');
exports.up = function (next) {
// Wait for mongodb Driver to be connected and get the mongodb object
dbConnect.mongodb.then(function (mongodb) {
// get the collection needed
var users = mongodb.collection('www_user');
//execute the query and get a cursor
var userCursor = users.find({});
// loop through the found docs
userCursor.each(function (err, doc) {
if (err) {
console.log(err);
} else {
// if it's the last doc null will be returned
// close the mongodb connection
// and finish the task
if (doc === null) {
mongodb.close();
next();
} else {
// Do what you need to do
console.log('Fetched:', doc);
}
}
});
});
};
exports.down = function (next) {
dbConnect.mongodb.then(function (mongodb) {
var users = mongodb.collection('www_user');
var userCursor = users.find({});
userCursor.each(function (err, doc) {
if (err) {
console.log(err);
} else {
if (doc === null) {
mongodb.close();
next();
} else {
console.log('Fetched:', doc);
}
}
});
});
};