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

问题描述 投票:3回答:2

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

我需要在一个查询中添加多个对象,检查每个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
2个回答
3
投票

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

-1
投票

架构:

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

}

© www.soinside.com 2019 - 2024. All rights reserved.