0

我在尝试注册新用户时收到错误 ValidationError: Path password is required。我是 Node、编程和身份验证的新手。

这是我拥有的用户模型和模式代码,我试图彻底评论它。

用户路由器

router.post("/register", async (req, res) => { try { let {email, password, passwordCheck, displayName} = req.body;

    // validate email, password and passwordCheck
    if (!email || !password || !passwordCheck)
        return res.status(400).json({ msg: "Not all fields have been entered." });
    if (password.length < 5)
        return res.status(400).json({ msg: "The password needs to be at least 5 characters long." });
    if (password !== passwordCheck)
        return res.status(400).json({ msg: "Passwords do not match. Enter the same password twice for verification." });


   //verify if the new user already exists in the MongoDB
    const existingUser = await User.findOne({ email: email });
    if (existingUser)
        return res.status(400).json({ msg: "An account with this email already exists." });

    if (!displayName) displayName = email; //if no display name, email is display name

    const salt = await bcrypt.genSalt(10); //creates random string used for hashing password
    const passwordHash = await bcrypt.hash(password, salt, function (err, hash) {
        if (err) {
            console.log('Issue with hashing bcrypt');
        }// else {console.log('Successful Hash: ' + hash);} add if error checking
    });
    //save new user to DB with hashed password
    const newUser = new User({
        email,
        "password":passwordHash,
        displayName,
    });
    console.log(newUser);
    const savedUser = await newUser.save(); //save the new user to database
    res.json(savedUser); //respond to front end with saved user

} catch (err) {
    console.log('Error registering user');
    res.status(500).json({ err });} });

用户模型

const userSchema = new mongoose.Schema({
email: {type: String, required: true, unique: true},
password: {type: String, required: true, minlength: 5},
displayName: {type: String} });
4

1 回答 1

1

你试过password: passwordHash而不是"password": passwordHash. 如果它没有帮助,那么你应该 console.log 你的 passwordHash 来检查它是否有一个值。

于 2020-11-17T04:50:38.613 回答