“error”: “创建用户时无法读取未定义的属性(读取’_id’)”

huangapple go评论67阅读模式
英文:

"error": "Cannot read properties of undefined (reading '_id')" when creating user

问题

我正在尝试为一个Web应用程序添加一些身份验证,并且我正在使用一个用于使用mongoose进行注册的函数,注册函数如下:

userSchema.statics.signup = async function(username, email, password){
	
	// 验证
	if(!email || !password || !username){
		throw Error('所有字段都是必填的');
	}
	if(!validator.isEmail(email)){
		throw Error('电子邮件无效');
	}
	if(!validator.isStrongPassword(password)){
		throw Error('密码不够强');
	}

	const userExists = await this.findOne({username});
	const emailExists = await this.findOne({email});

	if(userExists){
		throw Error('用户名已被使用')
	}

	if(emailExists){
		throw Error('电子邮件已被使用')
	}

	const salt = await bcrypt.genSalt(10)
	const hash = await bcrypt.hash(password, salt);

	const user = await this.create({username, email, password: hash})

}

然后,在发送到POST请求的函数中调用了这个函数:

const signupUser = async (req, res) => {
    const {username, email, password} = req.body;

    try{
        const user = await User.signup(username, email, password);

        // 创建令牌
        const token = createToken(user._id);

        res.status(200).json({username,email,token})
    }catch(error){
        res.status(400).json({error: error.message})
    }
}

用户被成功创建,但问题出现在响应对象中,当我在Postman中发送请求时,我得到的响应是:

{
    "error": "无法读取未定义的属性(读取 '_id')"
}

我已经阅读了其他类似的StackOverflow问题,并尝试了那些解决方案,但没有一个起作用。我还在signupUser函数中记录了用户的值,它返回undefined,但在signup函数中,我也记录了user的值,它返回一个带有signupUser函数中所需数据的对象。

英文:

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

答案1

得分: 1

The issue is that the signup function returns nothing (or undefined). This line is the problem: const user = await User.signup(username, email, password); You're calling the signup function, and assigning its return value -- remember, nothing! -- to a variable. Then, when you try to access a property of said variable, you're getting an error because you're reading the properties of nothing. By adding a return statement to signup with the user variable you declared in the function, you should be able to fix the issue.

英文:

The issue is that the signup function returns nothing (or undefined). This line is the problem: const user = await User.signup(username, email, password); You're calling the signup function, and assigning its return value -- remember, nothing! -- to a variable. Then, when you try to access a property of said variable, you're getting an error because you're reading the properties of nothing. By adding a return statement to signup with the user variable you declared in the function, you should be able to fix the issue.

huangapple
  • 本文由 发表于 2023年5月11日 07:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定