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

标签 javascript mongodb mongoose mongodb-query

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

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

相关文章:

java - 如何通过属性配置 spring-data-mongodb 以使用副本集

c# - 更新 MongoDB 中嵌套实体数组中的属性

java - 为什么在 MongoDB 中使用 Rest api 时无法获得准确的数据?

node.js - Mongoose 随机文档非顺序

javascript - impress.js - 下一个和上一个按钮

javascript - 每个元素的 jQuery 动画

javascript - 打印Ionic2页面中的html内容

javascript - 阿拉伯内容复合词中单独字母的宽度

javascript - 使用 nodeJS 查询前 5 个查看项目(排序)的 Mongoose

node.js - 我怎么知道mongodb是否是由mongoose启动的?