I am trying to add some authentication to a web app and I am using a function for signing up with mongoose, the function for signing up is here:
userSchema.statics.signup = async function(username, email, password){
//validation
if(!email || !password || !username){
throw Error('All fields required');
}
if(!validator.isEmail(email)){
throw Error('Email is Not Valid');
}
if(!validator.isStrongPassword(password)){
throw Error('Password not strong enough');
}
const userExists = await this.findOne({username});
const emailExists = await this.findOne({email});
if(userExists){
throw Error('Username in use')
}
if(emailExists){
throw Error('Email in use')
}
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(password, salt);
const user = await this.create({username, email, password: hash})
}
and then this function is called in the function sent to the post request here:
const signupUser = async (req, res) => {
const {username, email, password} = req.body;
try{
const user = await User.signup(username, email, password);
//create token
const token = createToken(user._id);
res.status(200).json({username,email,token})
}catch(error){
res.status(400).json({error: error.message})
}
}
The user is created just fine but the issue is with the response object, when I send the request in postman I get the response back of:
{
“error”: “Cannot read properties of undefined (reading ‘_id’)”
}
I have read other stackoverflow questions similar that received this error and attempted those solutions but none of those have worked. I have also logged user to console in the signupUser function and it is returning undefined, but in the signup function I also logged the value of user and it returns an object with all of the data I wanted user in the signupUser function to return