如果不存在,Mongoose会将多个对象添加到数组中 [英] Mongoose add multiple object to array if not exist based
本文介绍了如果不存在,Mongoose会将多个对象添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据键将多个对象添加到数组?
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)
架构
new Schema({
additional: [
{
key: { type: String, required: true, unique: true },
label: { type: String, required: true }
}
]
})
请求有效载荷:
[ {key: "city", label: "CITY"}, {key: "gender", label: "GENDER"}
, {key: "city" ,label: "CITY1}, {key: "city2", label: "CITY"}]
预期结果:
[
{key: "city", label: "CITY"},
{key: "gender", label: "GENDER"},
{key: "city2", label: "CITY"}
]
我试图找到解决方案但找不到任何解决方案。
I tried to find solutions but couldn't find any.
推荐答案
您可以尝试使用 bulkWrite
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" }
]
查询批量更新文件
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 } } } }
])
这篇关于如果不存在,Mongoose会将多个对象添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文