mongodb - 无法在 Mongoose 中保存文档 - 所需的验证器因路径错误而失败

标签 mongodb mongoose

以下是我的架构:

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/

相关文章:

node.js - 使用动态 model.find 从 mongoose 查询结果

c# - 访问 lambda 表达式内泛型类型的属性

javascript - 在 Mongoose 中推送 ObjectId

node.js - 将项目添加到混合模式数组时,mongoose.save 的结果不正确

javascript - 如何提高这个 MongoDB/Mongoose 查询的性能?

node.js - Mongoose,是否可以在一次调用中保存时将父 ID 分配给子文档?

php - MongoDb 只更新数组中的一个值

node.js - 带有 upsert 的 Mongoose 重复键错误

mongoose - 如何从 Mongoose 模式中获取枚举值?

node.js - 项目没有从数据库中删除,该项目应该是 :item in the app. 删除 ('/todo/:item' ) int 下面的代码