DEV Community

Mohmed Ishak
Mohmed Ishak

Posted on

The 1 JavaScript Mistake That Costed Me 2 Days (As A Pretty Experienced Developer)

Hey, guys! Do you still remember the first time you encountered a serious bug in programming? I'm sure you got stuck like crazy and couldn't move on for days, weeks, or even months. In this article, I'll share with you a particular mistake that costed me 2 days, and my sanity.

Array From Hell in Node.js

Here's the task you wanna accomplish. Look at the code snippet below.

const endAVotingSession = asyncHandler(async (req, res) => {
  const votingSession = await VotingSession.find({
    _id: mongoose.Types.ObjectId(req.params.id),
  });

  let arrayThatWillBeModified = votingSession.candidates;

  for (let i = 0; i < arrayThatWillBeModified.length; i++) {
    // Modify the array
  }

  await VotingSession.updateOne({ _id: mongoose.Types.ObjectId(req.params.id) }, 
    {
      candidates: arrayThatWillBeModified
    }
  );
});
Enter fullscreen mode Exit fullscreen mode

What we're doing is that we're grabbing an array that is returned by MongoDB, and then modifying it, and finally updating it.

The question is, will it work?

Nope. It will throw an error. Wanna know the error? It took me 1 to 2 days to solve it. The error is, in the line which I wrote...

let arrayThatWillBeModified = votingSession.candidates;
Enter fullscreen mode Exit fullscreen mode

...we as developers might assume that candidates is an array (WHICH IS ABSOLUTELY TRUE), and we would do all sorts of things with it like I did here, where I wrote a loop that presumably modified the array.

The problem is, that array (votingSession.candidates) is a Mongoose array, and it seems that you can't just modify it. Instead, you need to convert it to JavaScript array, and then you can modify your array. The solution:

let arrayThatWillBeModified = votingSession.candidates.toObject();
// .toObject() converts Mongoose array to JavaScript array
Enter fullscreen mode Exit fullscreen mode

The not so cool thing is, even if you log that Mongoose array in console, everything would appear fine, and you'll see an array with the right data. That's it for today guys. If you like this article, leave a like. Thank you.

Top comments (1)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

It's been a while since I did any Mongoose but isn't it the fact that you modified the data in situ rather than treating it as immutable and making a copy - hence when you set it back in, it looked like you hadn't changed anything because the array was the same object?