'How to upsert object in Mongoose Array?

I want to edit an array with mongoose, if the object id already exist in the array, then it will create a new one, and if it exist, it will update.

My code:

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

When I run it, the array looks like that

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

And when I run it again with a different member name

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

All I want is to edit the object with an id, and create a new object if the id doesn't exist in the array, I don't know what's wrong with my code, if someone can help me

My schema:

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


Solution 1:[1]

You can use $reduce to iterate the array and conditionally update it through $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"
                  ]
                ]
              }
            }
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ray