Search code examples
node.jsmongodbexpressmongoosemern

Can't see where multiple call of res caused the error : Cannot set headers after they are sent to the client


I'm following a tutorial in the net. It's a MERN project with mongo/mongoose. When I have implemented the update function in the controller the following error has occured :

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I've seen the answers about similar issue where they say it's because there are 2 or multiple calls of res (res.json(), res.send() etc..), but I don't see where must I change this in the following function :

module.exports.updateUser = async(req, res) => {
if (!ObjectID.isValid(req.params.id))
    return res.status(400).send("ID unknown : " + req.params.id);

try {
    await UserModel.findOneAndUpdate({
            _id: req.params.id
        }, {
            $set: {
                bio: req.body.bio
            }
        },
        (err, docs) => {
            if (!err)
                return res.send(docs);
            if (err)
                return res.status(500).send({ message: err });
        }
    )
} catch (err) {
    return res.status(500).json({ message: err });
}

};


Solution

  • It may be that you've mixed up two different error handling patterns.

    You don't need try/catch if you're using built in error handling of findOneAndUpdate()

    
    await UserModel.findOneAndUpdate({
                _id: req.params.id
            }, {
                $set: {
                    bio: req.body.bio
                }
            },
            (err, docs) => {
                if (!err)
                    return res.send(docs);
                if (err)
                    return res.status(500).send({ message: err });
            }
    )
    
    

    and if you are using try/catch, you don't need findOneAndUpdate's error handling:

    try {
        const user = await UserModel.findOneAndUpdate({
                _id: req.params.id
            }, {
                $set: {
                    bio: req.body.bio
                }
            })
    
        return res.send(user)
    } catch (err) {
        return res.status(500).json({ message: err });
    }