Skip to content

Instantly share code, notes, and snippets.

@dbrugne
Last active March 24, 2022 21:50
Show Gist options
  • Save dbrugne/2a62d4dd88f11fa36b75 to your computer and use it in GitHub Desktop.
Save dbrugne/2a62d4dd88f11fa36b75 to your computer and use it in GitHub Desktop.
MongoDB bulk insert from mongoose models
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