如果不存在,Mongoose 将多个对象添加到数组中 [英] Mongoose add multiple object to array if not exist based

查看:21
本文介绍了如果不存在,Mongoose 将多个对象添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我需要在一个查询中添加多个对象,检查每个对象键是否不存在或重复,否则添加对象.(label 可以重复)

架构

新架构({额外的: [{键:{ 类型:字符串,必需:真,唯一:真},标签:{ 类型:字符串,必需:真}}]})

请求负载:

[ {key: "city", label: "CITY"}, {key: "gender", label: "GENDER"}, {key: "city" ,label: "CITY1}, {key: "city2", label: "CITY"}]

预期结果:

<预><代码>[{key: "city", label: "CITY"},{键:性别",标签:性别"},{key: "city2", label: "CITY"}]

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

解决方案

您可以尝试使用 bulkWrite mongodb 中的操作

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

const 有效载荷 = [{ key: "city", label: "CITY" }, { key: "gender", label: "GENDER" },{ key: "city", label: "CITY1" }, { key: "city2", label: "CITY" }]

查询批量更新文档

Model.bulkWrite(payload.map((data) =>({更新一:{过滤器:{'_id':'xxxx','additional.key':{$ne:data.key}},更新:{ $push: { 附加:数据 } }}}))})

哪个会像这样批量发送更新请求

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

How to add multiple objects to array based on key?

I need to add multiple objects in one query, check if each object key doesn't exist or duplicate, else add object. (label can be duplicate)

Schema

new Schema({
      additional: [
        {
          key: { type: String, required: true, unique: true },
          label: { type: String, required: true }
        }
      ]
})

request payload:

[ {key: "city", label: "CITY"}, {key: "gender", label: "GENDER"}
, {key: "city" ,label: "CITY1}, {key: "city2", label: "CITY"}]

Expected results:

[
 {key: "city", label: "CITY"},
 {key: "gender", label: "GENDER"},
 {key: "city2", label: "CITY"}
]

I tried to find solutions but couldn't find any.

解决方案

You can try using bulkWrite operation in mongodb

Suppose you have following payload to update

const payload = [
  { key: "city", label: "CITY" }, { key: "gender", label: "GENDER" },
  { key: "city", label: "CITY1" }, { key: "city2", label: "CITY" }
]

Query to update documents in bulk

Model.bulkWrite(
  payload.map((data) => 
    ({
      updateOne: {
        filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } },
        update: { $push: { additional: data } }
      }
    })
  )
})

Which will send a request in bulk to update like this

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

这篇关于如果不存在,Mongoose 将多个对象添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆