Created
May 30, 2017 20:10
-
-
Save cayasso/cb516f686a018c5354f984f6f29d2c6a to your computer and use it in GitHub Desktop.
Bulk writes in mongoose
This file contains hidden or 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
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