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

IT技术 javascript mongodb mongoose mongodb-query
2021-03-09 09:43:18

如何根据键将多个对象添加到数组?

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

我试图找到解决方案,但找不到任何解决方案。

1个回答

您可以尝试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 } } } }
])
对我不起作用。它添加了空文档。你测试过吗?
2021-04-21 09:43:18
它工作正常,只需要添加 _id: 'xxxxx' of specific doc
2021-05-16 09:43:18