How to add multiple objects to array based on key?
I need to add multiple objects in one query, check if each object key
doesn't exist or duplicate, else add object. (label
can be duplicate)
Schema
new Schema({
additional: [
{
key: { type: String, required: true, unique: true },
label: { type: String, required: true }
}
]
})
request payload:
[ {key: "city", label: "CITY"}, {key: "gender", label: "GENDER"}
, {key: "city" ,label: "CITY1"}, {key: "city2", label: "CITY"}]
Expected results:
[
{key: "city", label: "CITY"},
{key: "gender", label: "GENDER"},
{key: "city2", label: "CITY"}
]
I tried to find solutions but couldn't find any.
You can try using bulkWrite
operation in mongodb
Suppose you have following payload to update
const payload = [
{ key: "city", label: "CITY" }, { key: "gender", label: "GENDER" },
{ key: "city", label: "CITY1" }, { key: "city2", label: "CITY" }
]
Query to update documents in bulk
Model.bulkWrite(
payload.map((data) =>
({
updateOne: {
filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } },
update: { $push: { additional: data } }
}
})
)
})
Which will send a request in bulk to update like this
bulkWrite([
{ updateOne: { filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } }, update: { $push: { additional: data } } } },
{ updateOne: { filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } }, update: { $push: { additional: data } } } }
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With