I'm trying to create a register route but the post request return cannot read properties of undefined. reading 'name'. And the "existUser" always returns true even though theres no user with the email in the database. Is there something that i'm missing here ? heres my route -
router.post('/register', async (req, res) => {
try {
const user = new User({
name: req.body.name,
email: req.body.email,
password: crypto.AES.encrypt(req.body.password, process.env.CRYPTO_SEC).toString(),
dateOfBirth: req.body.dateOfBirth,
});
const existUser = await User.findOne({ email: user.email });
if (existUser) {
return res.status(400).json({ msg: "Email Already Exist!" });
} else {
try {
const newUser = await user.save();
res.status(200).json(newUser);
} catch (err) {
res.status(400).json({ msg: err.message });
}
}
} catch (err) {
res.status(400).json({ msg: "An Error Occured!" })
}
});
User model -
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
dateOfBirth: {
type: Date,
required: true
},
profilePicture: {
type: String,
required: false,
default: ""
},
});
module.exports = mongoose.model("Users", userSchema);
How do I solve this weird error.
probably the request body property is not being found.
confirm you are passing some middleware from bodyparser to express.
something like that:
const express = require('express');
const app = express();
app.use(express.json());