Mongoose - Increment object counter when added to array

Viewed 175

I'm trying to figure out what the most efficient way of doing this, preferably in one query. If I have an array...

[
  {
    name: "Eric",
    priority: 1
  {
[

If I append another object using $addToSet, how can I increment the counter? For example, if I add John...

[
  {
    name: "Eric",
    priority: 1
  },
  {
    name: "John",
    priority: 2
  {
]

I was thinking of something like this...

let room = await Room.findOneAndUpdate(
  { room_id: data.room_id },
  { 
    $addToSet: { 
      guest_list: { 
        name: data.name
      } 
    },
    "guest_list.$.priority": guest_list.length
  },
  { new: true }
);

I know this doesn't work, but it would be nice if I can get the length of the array and use that in the priority attribute as so...

"guest_list.$.priority": guest_list.length

What is the best way of doing this?

0 Answers
Related