0

After pushing a value to an array through a button click event, I need to get the length of the array, but I'm getting a value of 0. I've read tons of thread about async and await that regular methods or console.log executes first before async/promises, and that I should either use Promise.all or for loop, but I still couldn't make it work.

Here's the code:

client.on("interactionCreate", async (interaction) => {
    if (interaction triggers) {
        const queryVote = await db.collection("poll").findOneAndUpdate({pollId: "01"}, {$push: {"votes.$[elem].votes": userId}}, {arrayFilters: [{ "elem.answer": "Yes"}]});
        const voteLength = queryVote.value.votes[0].votes.length;
        console.log(voteLength);
    }
})

So let say user01 id gets added as the first id on the votes array, then the length should return 1, but it's returning 0.

Here's the mongodb document

[
  {
    "pollId": "01",
    "votes": [
      {
        "answer": "Yes",
        "votes": [
          "user01"
        ]
      },
      {
        "answer": "No",
        "votes": []
      },
      
    ]
  }
]
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
user874737
  • 469
  • 1
  • 9
  • 24
  • 3
    findOneAndUpdate returns the orginal document by default, not the updated one. You need to add the returnNewDocument parameter and set it to true, or the returnDocument parameter and set it to _after_ – GreenChicken Jun 26 '23 at 12:02
  • @GreenChicken, oh, i didn't know that. thank you. – user874737 Jun 26 '23 at 12:26

0 Answers0