【问题标题】:Mongoose add multiple object to array if not exist based如果不存在,Mongoose 将多个对象添加到数组
【发布时间】:2019-01-18 22:14:36
【问题描述】:

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

我需要在 one 查询中添加多个对象,检查每个 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"}
]

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

【问题讨论】:

    标签: javascript mongodb mongoose mongodb-query


    【解决方案1】:

    你可以尝试在mongodb中使用bulkWrite操作

    假设您有以下有效负载要更新

    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 } } } }
    ])
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2020-01-12
    • 2019-02-13
    • 2020-02-23
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多