Monday, 13 March 2017

NodeJS: Can't set headers after they are send

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('/');
         }

 });



via zoenightshade

No comments:

Post a Comment