Home > Software engineering >  res.send is not a function and error is not handled
res.send is not a function and error is not handled

Time:09-08

I am getting this strange error from my function that creates users for my mongoose database. everything is correctly working, the user is being created. But res.send is not working so I dont get any thing back, instead I get an error

Here is the code

module.exports.newUser = (req, res) =>{
    const newUser = new Users({
        name: req.params.userName,
        mail: req.body.mail,
        password: req.body.password,
        img: req.body.img,
    })
    
    newUser.save((err, res) => {
        if (!err){
            return res.send("successfully created user!");
        }else{
            return res.send(err.message);
        }
    });
};

here is the error:

node:events:368
  throw er; // Unhandled 'error' event
  ^

TypeError: res.send is not a function
    at C:\Users\tlege\OneDrive\Masaüstü\project 1\untitled_project\Server\src\controllers\userController.js:45:24
    at C:\Users\tlege\OneDrive\Masaüstü\project 1\untitled_project\Server\node_modules\mongoose\lib\model.js:5097:18
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
Emitted 'error' event on Function instance at:
    at C:\Users\tlege\OneDrive\Masaüstü\project 1\untitled_project\Server\node_modules\mongoose\lib\model.js:5099:15
    at processTicksAndRejections (node:internal/process/task_queues:78:11)

What is the problem here, I really dont get it

CodePudding user response:

you just have to change the code a bit,

Try this :

module.exports.newUser = (req, res) =>{
    const newUser = new Users({
        name: req.params.userName,
        mail: req.body.mail,
        password: req.body.password,
        img: req.body.img,
    })
    
    newUser.save((err, result) => {
        if (!err){
            return res.send("successfully created user!");
        }else{
            return res.send(err.message);
        }
    });
};

Explaination : You were overwriting the res received from the request by the res received from the save method.

I hope this answer helps you!

  • Related