mongoose NodeJS + Mongo数据库:验证错误:用户验证失败:username:需要路径'username'

yhived7q  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(171)

当我尝试使用Mongoose将新文档(用户)保存/创建到Mongo DB时,尽管为所有值提供了正确的数据类型,但仍出现以下验证错误:

验证错误:用户验证失败:用户名:需要路径username

我是 NodeJS 和Mongo DB的初学者,因此我不能理解哪里出了问题。
我还添加了以下模块:

  • 特快专递
  • 蒙戈
  • Mongoose
  • 正文解析器

请参阅以下内容了解更多详情:

详细错误:

{
"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)
        }
    })
};

我只是不明白,为什么我得到这个验证错误。谁能告诉我这个。谢谢你的帮助。

nuypyhwy

nuypyhwy1#

您输入了一个错字:

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)
        }
    })
};
lx0bsm1f

lx0bsm1f2#

我确实遇到了这个问题,解决它的方法只是在您的server.js中添加这些行:

app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(express.json());

并确保安装了Cors和Express。
我的问题是,我没有只添加这一行:

app.use(express.json());

添加后,数据被完美保存。

相关问题