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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果不存在,Mongoose会将多个对象添加到数组中相关的知识,希望对你有一定的参考价值。

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

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

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

答案

您可以尝试在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 } } } }
])
另一答案

架构:

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

路线:

router.post('/testdata',function(req,res){ let exp = new 
        Exp({additional:req.body}); exp.save((err,data)=> { if(!err){res.send(data)})})

有效载荷:

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

]

输出:

db.exps.find()。漂亮的()

{
"_id" : ObjectId("5b6f0b72652f2f3d4d0caca7"),
"additional" : [
    {
        "_id" : ObjectId("5b6f0b72652f2f3d4d0cacab"),
        "key" : "city",
        "label" : "CITY"
    },
    {
        "_id" : ObjectId("5b6f0b72652f2f3d4d0cacaa"),
        "key" : "gender",
        "label" : "GENDER"
    },
    {
        "_id" : ObjectId("5b6f0b72652f2f3d4d0caca9"),
        "key" : "city",
        "label" : "CITY1"
    },
    {
        "_id" : ObjectId("5b6f0b72652f2f3d4d0caca8"),
        "key" : "city2",
        "label" : "CITY"
    }
],
"created_at" : ISODate("2018-08-11T16:14:42.766Z"),
"updated_at" : ISODate("2018-08-11T16:14:42.766Z"),
"__v" : 0

}

以上是关于如果不存在,Mongoose会将多个对象添加到数组中的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose Schema中Array内的重复值

如果未找到值,则使用 mongoose 将对象添加到数组中,否则更新字段

使用 mongoose 将多个不存在的文档插入 MongoDB

使用 mongoose 将多个不存在的文档插入 MongoDB

Mongoose:如果值存在于对象数组中的数组中,则过滤数据

检查对象值是不是存在于 Javascript 对象数组中,如果不存在则将新对象添加到数组