-
-
Save dqtweb/9c03f9ecf5a3b00d0ea2fb462acf091b to your computer and use it in GitHub Desktop.
MongoDB bulk insert from mongoose models
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 mongoose = require('mongoose'); | |
var hitSchema = mongoose.Schema({ | |
text: String, | |
music: String | |
}); | |
hitSchema.statics.bulkInsert = function(models, fn) { | |
if (!models || !models.length) | |
return fn(null); | |
var bulk = this.collection.initializeOrderedBulkOp(); | |
if (!bulk) | |
return fn('bulkInsertModels: MongoDb connection is not yet established'); | |
var model; | |
for (var i=0; i<models.length; i++) { | |
model = models[i]; | |
bulk.insert(model.toJSON()); | |
} | |
bulk.execute(fn); | |
}; | |
var HitModel = mongoose.model('Hit', hitSchema); | |
mongoose.connect(); | |
mongoose.connection.on("open", function(err, conn) { | |
var model, models = []; | |
for (var i=0; i<4; i++) { | |
model = new HitModel(); | |
model.text = 'lalalalala'; | |
model.music = 'tou dou dou dou'; | |
models.push(model); | |
} | |
HitModel.bulkInsert(models, function(err, results) { | |
if (err) { | |
console.log(err); | |
process.exit(1); | |
} else { | |
console.log(results); | |
process.exit(0); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment