Reputation: 159
I'm having trouble when executing this command. It happens when i delete multiple items. NodeJS returns an error but when i restart the server, the items are successfully deleted.
Here is my code:
router.delete('/:userID/hobbies', function(req, res, next)
{
var userID = req.params.userID;
if (req.user._id == userID)
{
hobbiesData.find({owner: userID, isComplete: true},function(err, userHobbies) {
userHobbies.forEach(function (userHobby)
{
usersData.findByIdAndUpdate(
userID,
{ $pull: { hobbies: userHobby._id }},
{ new: true, upsert: true },
function(err, results)
{
if(err)
{
return res.end(err);
}
else
{
userHobby.remove(function(err) {
if(err)
{
return res.end(err);
}
else
{
return res.json(results);
}
});
}
}
);
});
});
}
else
{
res.redirect('/');
}
});
Upvotes: 0
Views: 29
Reputation: 36349
The error tells you what happened, you're calling res.end for each item, but you can only do that once per request. Note that end() is called under the hood for send() and json() and so on.
Either respond without waiting for all the updates to happen, or do it after they've all happened. But don't do it for each delete.
Upvotes: 2