Skip to content

Instantly share code, notes, and snippets.

@chrishamant
Created May 4, 2011 04:37
Show Gist options
  • Save chrishamant/954765 to your computer and use it in GitHub Desktop.
Save chrishamant/954765 to your computer and use it in GitHub Desktop.
some code to seed a database with fixtures
var sys = require("sys");
var fs = require('fs');
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSONNative;
var _ = require('nimble');
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
var seedDB = function(filename,collection_name,db){
return function(cb){
fs.readFile(__dirname + filename, "utf-8",function(err,file){
if(err) throw err;
var data = JSON.parse(file);
db.dropCollection(collection_name,function(){
db.collection(collection_name,function(err,collection){
collection.insert(data,{"safe" : true},function(err,data){
console.info("wrote "+ data.length + " records");
return cb();
});
});
});
});
}
}
var _db = new Db('dbname', new Server(host, port, {}), {native_parser:true});
_db.open(function(err,db){
if(err) return console.log(err);
_.parallel([
seedDB('/something1.json','something1',db),
seedDB('/something2.json','something2',db)
],function(err){
_db.close();
});
});
[{"foo":"bar","baz" :1,"json" : "ftw"},{"a":1,"b":2}]
[{"foo":"bar","baz" :1,"json" : "ftw"},{"a":3,"b":4}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment