gpt4 book ai didi

javascript - 如果不存在, Mongoose 将多个对象添加到数组

转载 作者:可可西里 更新时间:2023-11-01 09:38:30 24 4
gpt4 key购买 nike

如何根据键向数组中添加多个对象?

我需要在一个 查询中添加多个对象,检查每个对象键 是否不存在或不重复,否则添加对象。 (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com