Last active
June 30, 2019 19:32
-
-
Save christophrus/977e62dedbeaaf7b2e143ba7321bee2a to your computer and use it in GitHub Desktop.
mongoose conditional update/insert test
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
const mongoose = require('mongoose'); | |
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true }); | |
mongoose.set('useCreateIndex', true); | |
mongoose.set('useFindAndModify', false); | |
const { Schema } = mongoose; | |
const testSchema = new Schema({ | |
name: String, | |
server: String, | |
level: Number | |
}); | |
testSchema.index({ name: 1, server: 1 }); | |
const Test = mongoose.model('Test', testSchema); | |
/* const testCollection = [ | |
{ name: 'Jean', server: 'Alpha', level: 9 }, | |
{ name: 'Anna', server: 'Beta', level: 17 }, | |
{ name: 'Jean', server: 'Beta', level: 10 } | |
]; | |
Test.insertMany(testCollection); */ | |
const inputs = [ | |
// { name: 'Victor ', server: 'Alpha', level: 22 }, // #1 document with new index, should be added to the collection | |
// { name: 'Jean', server: 'Alpha', level: 10 }, // #2 document with existing index but higher level, collection should be updated | |
// { name: 'Jean', server: 'Alpha', level: 9 } // #3 document with existing index but equal level, nothing should happen | |
{ name: 'Jean', server: 'Alpha', level: 8 } // #3 document with existing index but lower level, nothing should happen | |
]; | |
const bulkInput = inputs.map(input => ({ | |
updateOne: { | |
filter: { name: input.name, server: input.server, level: { $lte: input.level } }, | |
upsert: true, | |
update: { $set: { name: input.name, server: input.server, level: input.level } } | |
} | |
})); | |
Test.bulkWrite(bulkInput).then(result => { | |
console.log('inserted:', result.nUpserted, 'updated:', result.nModified); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment