Skip to content

Instantly share code, notes, and snippets.

@1nstinct
Last active February 2, 2016 09:43
Show Gist options
  • Save 1nstinct/0a60e6e6ad24f92efce3 to your computer and use it in GitHub Desktop.
Save 1nstinct/0a60e6e6ad24f92efce3 to your computer and use it in GitHub Desktop.
NodeJs+MongoDB+Migrations
/*
This script uses https://github.com/tj/node-migrate module for NodeJs
Installing:
1. npm install -g grunt-cli
2. npm install grunt --save-dev
3. npm install migrate -g
Running from console:
1. migrate create migration_script
2. migrate up migration_script.js
*/
'use strict'
var MongoClient = require('mongodb').MongoClient,
url = 'mongodb://localhost:27017/restaurant';
exports.up = function (next) {
MongoClient.connect(url, function (err, db) {
var collection = db.collection('product_categories'),
Q = require('q');
// grouping query
collection.aggregate([
{
$sort: {
createdAt: 1
}
},
{
$group: {
_id: "$restaurant",
ids: {$push: "$_id"}
}
}
], function (err, restaurants) {
// response
if(err) {
console.error(err);
} else {
var ObjectID = require('mongodb').ObjectID,
promises = [];
for(var i in restaurants) {
for(var k in restaurants[i].ids) {
promises.push((function() {
var deferred = Q.defer();
// add sortorder
collection.updateOne({_id: new ObjectID(restaurants[i].ids[k]) }, {$set:{sortorder: parseInt(k)}}).then(function(result){
deferred.resolve(true);
});
return deferred.promise;
})());
}
}
Q
.allSettled(promises)
.then(function(data) {
// creating index
collection.createIndex({restaurant:1, sortorder:1}
, {unique:true}, function(err, indexName) {
if(err) console.error(err);
else {
next();
}
db.close();
});
}).catch(function(error) {
console.error(error.message);
});
}
});
});
};
exports.down = function (next) {
MongoClient.connect(url, function (err, db) {
var collection = db.collection('product_categories');
// drop index
collection.dropIndex("restaurant_1_sortorder_1", function(err, result) {
// drop all sortorder
var o = {w:1};
o.multi = true;
collection.updateMany({}, {$unset:{sortorder:""}}, o, function(err, r) {
db.close();
next();
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment