代码之家  ›  专栏  ›  技术社区  ›  Liam

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

  •  3
  • Liam  · 技术社区  · 6 年前

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

    查询,检查是否每个 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"}
    ]
    

    我试图找到解决办法,但没有找到。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Ashh    6 年前

    你可以试着用 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 } } } }
    ])