当我尝试使用Mongoose向Mongo DB保存/创建新文档(用户)时,尽管为所有值提供了正确的DataType,但我得到以下验证错误:
ValidationError:用户验证失败:用户名:路径username
是必需的。
我是Node JS和Mongo DB的初学者。因此,我无法理解出了什么问题。
我还添加了以下模块:
请参阅下文了解更多详情:
详细错误:
{
"errors": {
"username": {
"message": "Path `username` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "username"
},
"kind": "required",
"path": "username",
"$isValidatorError": true
}
},
"_message": "User validation failed",
"message": "User validation failed: username: Path `username` is required.",
"name": "ValidationError"
}
用户架构/型号:
var mongoose = require("mongoose");
var userSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
}
});
mongoose.model("User", userSchema, "users");
用户控制器:
var register = function (req, res) {
console.log("Registering User.");
var firstName = req.body.firstname;
var lastName = req.body.lastname;
var userName = req.body.username;
var password = req.body.password;
User
.create({
firstName: firstName,
lastName: lastName,
userName: userName,
password: password
}, function (err, user) {
if (err) {
console.log("Error creating User: ", err);
res
.status(400)
.json(err)
} else {
console.log("User Created: ", user);
res
.status(201)
.json(user)
}
})
};
我只是不明白,为什么我收到此验证错误。 任何人都可以指导我完成这件事。谢谢你的帮助。
答案 0 :(得分:1)
你写了一个错字:
User
.create({
firstName: firstName,
lastName: lastName,
username: userName, // the property is "username" in model
password: password
}, function (err, user) {
if (err) {
console.log("Error creating User: ", err);
res
.status(400)
.json(err)
} else {
console.log("User Created: ", user);
res
.status(201)
.json(user)
}
})
};