Nodemon is getting carshed and cliendt side response is not getting when user name already exits in the database

Viewed 17

My nodmon server is getting crashed and not getting the response on the client side(react frontend). It happens when the user name already exists in the database. Also, try block is not catching the throwing error.

exports.updateUser = async(req, res) => {
    try {
        if (req.body.userId === req.params.id) {
            if (req.body.userName || req.body.email) {
                await User.findOne({
                    $or: [{
                            email: req.body.email,
                        },
                        {
                            username: req.body.userName,
                        },
                    ],
                }).exec((err, user) => {
                    if (err) {
                        throw {
                            code: 400,
                            error: err,
                        };
                    } else if (user) {
                        if (user.username === req.body.userName) {
                            throw {
                                code: 400,
                                error: { error: "User Name already exists" },
                            };
                        } 
                    //     if (user.email === req.body.email) {
                    //     throw {
                    //         code: 400,
                    //         error: "Email already exists",
                    //     };
                    //   }
                    }
                });
            }
            console.log(e);
            if (req.body.password) {
                const salt = await bcrypt.genSalt(10);
                req.body.password = await bcrypt.hash(req.body.password, salt);
            }
            await User.findByIdAndUpdate(
                req.params.id, { $set: req.body }, { new: true }
            ).exec((err, user) => {
                if (err) {
                    throw {
                        code: 500,
                        error: err,
                    };
                }
                if (user) {
                    return res.status(200).json("User Updated successfully!"); // here error is showing.
                }
            });
        } else {
            throw {
                code: 401,
                error: "You can update only your account!",
            };
        }
    } catch(e) {
       return res.status(e.code).json(e.error);
    }
};
0 Answers
Related