如何在 Mongoose 数组中插入对象?

How to upsert object in Mongoose Array?

我想用mongoose编辑一个数组,如果对象id已经存在于数组中,那么它会创建一个新的,如果存在,它会更新。

我的代码:

const data = { id: 1, member: 'Test' };
Schema.updateOne(
                { id: guild.id },
                {
                    $addToSet: {
                        users: data
                    }
                },
                {
                    arrayFilters: [
                        {
                            [`users.id`]: data.id
                        }
                    ],
                }
            )
        }

当我运行它时,数组看起来像那样

[
  { "id": 1, "member": "Test" }
]

然后当我 运行 它再次使用不同的成员名称时

[
  { "id": 1, "member": "Test" },
  { "id": 1, "member": "Adam" }
]

我只想用一个 id 编辑对象,如果数组中不存在 id 则创建一个新对象,我不知道我的代码有什么问题,如果有人可以帮助我

我的架构:

const cluster = mongoose.Schema({
    id: { 'type': String, unique: true, index: true, required: true },
    users: []
});

可以使用$reduce迭代数组,通过$cond有条件更新。

db.collection.update({
  _id: "guild1"
},
[
  {
    $addFields: {
      users: {
        "$reduce": {
          "input": "$users",
          "initialValue": [
            // put your to-be object here
            {
              "id": 1,
              "member": "Adam"
            }
          ],
          "in": {
            "$cond": {
              "if": {
                "$in": [
                  "$$this.id",
                  "$$value.id"
                ]
              },
              "then": "$$value",
              "else": {
                "$concatArrays": [
                  "$$value",
                  [
                    "$$this"
                  ]
                ]
              }
            }
          }
        }
      }
    }
  }
])

这里是Mongo playground供大家参考。