Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophrus/977e62dedbeaaf7b2e143ba7321bee2a to your computer and use it in GitHub Desktop.
Save christophrus/977e62dedbeaaf7b2e143ba7321bee2a to your computer and use it in GitHub Desktop.
mongoose conditional update/insert test
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true });
mongoose.set('useFindAndModify', false);
const { Schema } = mongoose;
const testSchema = new Schema({
name: String,
server: String,
level: Number
});
const Test = mongoose.model('Test', testSchema);
/*
// for initializing a test collection
const testCollection = [
{ name: 'Jean', server: 'Alpha', level: 9 },
{ name: 'Anna', server: 'Beta', level: 17 },
{ name: 'Jean', server: 'Beta', level: 10 }
];
Test.insertMany(testCollection, (err, docs) => {
console.log(docs);
}); */
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 or lower level, nothing should happen
{ name: 'Jean', server: 'Alpha', level: 8 } // #3 document with existing index but equal or lower level, nothing should happen
];
// filter functions
const byChanged = collection => document =>
collection.findIndex(
find =>
find.name === document.name && find.server === document.server && find.level < document.level
) !== -1;
const byNew = collection => el =>
collection.findIndex(find => find.name === el.name && find.server === el.server) === -1;
// helper function
const compileUpdatePromises = changedInputs => {
const updatePromises = [];
changedInputs.forEach(input => {
updatePromises.push(
new Promise((resolve, reject) => {
Test.findOneAndUpdate({ name: input.name, server: input.server }, input, (err, data) => {
if (data) {
resolve('updated');
}
});
})
);
});
return updatePromises;
};
Test.find({}, async (err, documents) => {
if (err) return console.log(err);
if (documents.length > 0) {
const changedInputs = inputs.filter(byChanged(documents));
const newInputs = inputs.filter(byNew(documents));
const insertResult = await Test.insertMany(newInputs);
const inserted = insertResult.length;
const updateResults = await Promise.all(compileUpdatePromises(changedInputs));
let updated = 0;
updateResults.forEach(updateResult => {
updated = updateResult === 'updated' ? updated + 1 : updated;
});
console.log('updated:', updated);
console.log('inserted:', inserted);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment