猫鼬将多个对象添加到数组(如果不存在的话)

时间:2018-08-11 15:11:41

标签: javascript mongodb mongoose mongodb-query

如何基于键将多个对象添加到数组?

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

答案 0 :(得分: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 :(得分:-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()。pretty()

{
"_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

}