Sunday, 7 May 2017

nodejs mongoose remove hits Error: Can't set headers after they are sent

I am using mongoose to read and update and remove some documents.
The find and update and remove are working fine. Except the last data.remove(); which is not being removed and hits an error.
I am getting this error in my code below:

events.js:160
      throw er; // Unhandled 'error' event
      ^
    Error: Can't set headers after they are sent.

and the line that it is pointing to is:

res.status(200).json({
                success: true
            });

at the end of the code.

router.post('/some/route', function (req, res) {
    if (req.isLoggedIn()) {
        return res.status(403).json({});
    }
    MyModel.findById(req.user._id,function (err, data) {
        if(err || data.rights !== 'super'){
            return res.status(403).json({});
        }
        if(req.body.writer){
            Books.update(
                { writer : req.body.id},
                { $set : { writer : req.body.writer} },
                function (err) {
                    if(err){
                        res.status(500).send(err);
                    }
                    else{
                        res.status(200).send('updated successfully.');
                    }
                }
            );
        }else{
            Books.remove({writer: req.body.id}, function(err){
                if (err){ return console.log(err)}
            });
        }

        MetaInfo.findOneAndRemove({_id: req.body.id}, function (err, data) {
            console.log(err);            
        });
        Archive.findOne({_id: req.body.id},function (err, data) {

            smtpTransporter.sendMail({...}, function (error, response) {
                if (error) {
                    console.log(error);
                } else {
                    console.log("Mail sent");
                }
                smtpTransporter.close();
            });

            data.remove();
            if (err) {
                console.log(err);
                return res.status(200).json({
                    success: false,
                    message: 'server error',
                    err: err
                });
            }
            res.status(200).json({
                success: true
            });
        })
    });
});



via cplus

No comments:

Post a Comment