'mongoose | batch insert and update if already exists
I have the following Schema
const domain = new Schema({
created: { type: Date, default: Date.now },
last_update: { type: Date, default: Date.now },
domain: String,
});
index in schema is domain
.
I want to do batch insert for this collection.
but if a document exist I only want it to be updated (and not double inserted)
for example: if the collection has the following domains:
gmail.com, yahoo.com, msn.com
And i want to insert and update the following data:
let data = [{domain:"gmail.com", test: true}, {domain:"fake.com", test: false}]
I expect the collection to add fake.com
and to update gmail.com
what is the correct way to do so?
Solution 1:[1]
You use db.collection.update() with the upsert
option:
Upsert: If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.
Domains.update( // Or db.domains with mongodb directly
{
domain: 'www.something.com'
},
{
domain: 'www.something.com'
},
{
upsert: true
}
)
If you're targeting multiple documents by the unique domain key, I'm not aware that there is a way to do it in a single batch command.
Solution 2:[2]
for insert and update if already exists. here is my solution-
let addSurveyQuestion = [];
fields.forEach(async (item) => {
addSurveyQuestion.push({
updateOne: {
filter: { slug: item.cid },
update: {
title: item.label,
survey_id,
image: item.image ? item.image : null,
description: item.field_options.description,
options: optionData,
other_option: item.field_options.include_other_option
? item.field_options.include_other_option
: null,
type: item.field_type,
slug: item.cid,
required: item.required,
},
upsert: true,
},
});
await SurveyQuestion.bulkWrite(addSurveyQuestion);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dominic |
Solution 2 | Al Imran Hossain |