Home > Enterprise >  Mongoose: cannot set headers after they are sent to the client
Mongoose: cannot set headers after they are sent to the client

Time:03-22

im trying to build login system with nodejs-mongodb. My controller finds user when i post fields but then it doesn't let me use res.send() catch block handling something here my codes:

Controller

exports.loginUser = async (req, res) => {
    try {
        const {email,password} = req.body;

        await User.findOne({email},(err,user) => {
          if(user){
             bcrypt.compare(password, user.password,(err,same) => {
                if(same){
                    res.status(200).json({
                        status:"Login Success"
                    });
                }
             });
          }
        });
    } catch(error){
        res.status(400).json({
            status: "Failed",
            error
        })
    }
};

Schema

const UserSchema = new Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true,
        unique:true
    },
    password:{
        type:String,
        required:true
    }
});

CodePudding user response:

I removed the findOne() method's callback function and used the .then(). It solved.

  • Related