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
}
);
});
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;
...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
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.