Skip to content

Instantly share code, notes, and snippets.

@bitmage
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitmage/7b3571683d2496459982 to your computer and use it in GitHub Desktop.
Save bitmage/7b3571683d2496459982 to your computer and use it in GitHub Desktop.
simple seed data script
module.exports = {
Student: [
{name: 'Bob', email: 'bob@foo.com'},
{name: 'Susy', email: 'susy@foo.com'}
]
};
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