如何根据键向数组中添加多个对象?
我需要在一个 查询中添加多个对象,检查每个对象键
是否不存在或不重复,否则添加对象。 (label
可以重复)
架构
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"}
]
我试图找到解决方案,但找不到。
最佳答案
您可以尝试使用 bulkWrite
mongodb中的操作
假设您有以下要更新的负载
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 } }
}
})
)
})
像这样批量发送更新请求
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 } } } }
])
关于javascript - 如果不存在, Mongoose 将多个对象添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51801033/