Skip to content

Instantly share code, notes, and snippets.

@cayasso
Created May 30, 2017
Embed
What would you like to do?
Bulk writes in mongoose
const mongoose = require('mongoose')
const { Types, Schema } = mongoose
// Connect to mongo
mongoose.connect('mongodb://localhost/bulk');
// Set model schema
const ArticleSchema = new Schema({
title: {
type: String,
required: true
},
published: {
type: Boolean,
default: false
}
});
// Register model
const Article = mongoose.model('Article', ArticleSchema);
// Insert function
function insertOne(document) {
return {
insertOne: {
document
}
}
}
// Update function
function updateOne(filter, update) {
return {
updateOne: {
filter,
update: {
$set: update
}
}
}
}
function deleteOne(filter) {
return {
deleteOne: {
filter
}
}
}
// Ids holder
const ids = []
// Create 20 object ids
for (let i = 0; i < 20; i++) {
ids.push(Types.ObjectId())
}
// Creeate bulk inserts
const insertOps = ids.map((_id, i) => insertOne({ _id, title: `Hi ${i}` }))
// Create bulk updates
const updateOps = ids.map(_id => updateOne({ _id },{ published: true }))
// Create bulk deletes
const deleteOps = ids.map(_id => deleteOne({ _id }))
// Execute bulk insert and update ops
Article.bulkWrite([...insertOps, ...updateOps]).then(res => {
console.log(res)
// Fetch all docs
Article.find().then(res => {
console.log(JSON.stringify(res, null, 2))
})
// Execute bulk delete ops
Article.bulkWrite(deleteOps).then(res => {
console.log(res)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment