Last active
August 29, 2015 14:13
-
-
Save bitmage/7b3571683d2496459982 to your computer and use it in GitHub Desktop.
simple seed data script
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
module.exports = { | |
Student: [ | |
{name: 'Bob', email: 'bob@foo.com'}, | |
{name: 'Susy', email: 'susy@foo.com'} | |
] | |
}; |
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
var initial_data = require('./initial_data') | |
, async = require('async') | |
, m = require('mongoose').models; | |
module.exports = function(gulp) { | |
gulp.task('seed', function(done) { | |
// TODO: delete data or drop and recreate DB | |
function importCollection(coll, next, model_name) { | |
function createRecord(data, nextRecord) { | |
return m[model_name].create(data, nextRecord); | |
}; | |
// create each record | |
return async.map(coll, createRecord, next); | |
}; | |
// import each collection | |
return objMapAsync(initial_data, importCollection, function(err, results) { | |
if (err == null) {console.log(results);} | |
done(err); | |
}); | |
}); | |
}; | |
// for reference, this is just a helper function I created | |
// the map included in async only works with arrays | |
// this one works with objects | |
function objMapAsync(obj, iter, done) { | |
function wrappedIter(results, key, next) { | |
function interpret(err, result) { | |
results[key] = result; | |
next(err, results); | |
}; | |
iter(obj[key], interpret, key); | |
}; | |
async.reduce(Object.keys(obj), {}, wrappedIter, done); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment