以下是我的架构:
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: false
}
});
现在,当我尝试保存上述模式的文档时,出现以下错误:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' } } }
以上是mongoose保存时返回的错误对象。我搜索了这个错误,但不明白哪里出了问题。我要保存的文档如下:
{
username: "foo"
password: "bar"
}
知道这是什么意思吗?我也搜索了 Mongoose 文档,但在验证部分找不到任何内容。
最佳答案
首先,您在 foo
之后缺少一个逗号 (,)。
现在,{ username: "foo", password: "bar"}
JSON 是通过 http 发送的,我们是服务器端代码中的实际对象吗?
如果是,请尝试 console.log(youVariable.username)
并查看它是否显示 undefined
或值 foo
。如果您看到 undefined
,那么您的对象没有被正确解析。
您可以确保发送 POST 请求的人在 header 中发送“application/json”,您可能会收到其他内容,因此您的 JSON 不会被解析为有效的 javascript 对象。
关于mongodb - 无法在 Mongoose 中保存文档 - 所需的验证器因路径错误而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16263540/