0

I'm trying to code a little social media using express and mongoose principally, and I got the error "ERR_HTTP_HEADERS_SENT" while running this code. How am I supposed to fix this ?

const UserModel = require("../models/user.model");
const ObjectID = require("mongoose").Types.ObjectId;


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,
        },
      },
      { new: true, upsert: true, setDefaultsOnInsert: true },
      (err, docs) => {
        if (!err) return res.status(200).json(docs);
        if (err) return res.status(500).json({ message: err });
      }
    );
  } catch (err) {
    return res.status(500).json({ message: err });
  }
};
  • The error must come from some other part of your code that is executed when you make the problematic request. Can you share that request and also the relevant code? – Heiko Theißen Jul 28 '22 at 14:22
  • I'm executing this code on Postman, by selecting "PUT" and entering {"bio": "..."}. The problem can possibly come from this part of code (the routes): `const userController = require('../controllers/user.controller') const router = require("express").Router(); const authController = require("../controllers/auth.controller"); // auth router.post("/register", authController.signUp); router.get('/', userController.getAllUsers); router.get('/:id', userController.userInfo) router.put('/:id', userController.updateUser) module.exports = router;` – Alexandre Calcio Gaudino Jul 28 '22 at 15:47
  • and when I'm a checking on the database, I can see the bio I have just modified – Alexandre Calcio Gaudino Jul 28 '22 at 15:55
  • You must check if some earlier code already executes `res.send` or something similar and then calls `next()`. – Heiko Theißen Jul 28 '22 at 16:19
  • One function used for showing a profile is doing this. Do I need to change something? – Alexandre Calcio Gaudino Jul 28 '22 at 17:41
  • After sending a response with `res.send` or similar, you must not send another or call `next()`. To just log something, use `console.log`. – Heiko Theißen Jul 28 '22 at 18:37
  • Actually I found out it was a problem with the await and the findAndReplace. But anyway thanks a lot for your help – Alexandre Calcio Gaudino Jul 29 '22 at 09:43

0 Answers0