为什么在mongoose中添加要求的字段会导致验证错误?

时间:2016-09-01 17:06:36

标签: node.js mongodb mongoose schema

在我的架构中我有

const userSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: true
  }
});

但是,当我尝试使用Postman测试时,创建一个假用户:

{
  "email": "amh@gmail.com",
  "password": "1232",
  "firstName": "alanh"
}

mongoose然后抛出这个:

ValidationError: user validation failed
    at MongooseError.ValidationError (/Users/alanh/test2/auth/server/node_modules/mongoose/lib/error/validation.js:22:11)
    at model.Document.invalidate (/Users/alanh/test2/auth/server/node_modules/mongoose/lib/document.js:1410:32)
    at /Users/alanh/test2/auth/server/node_modules/mongoose/lib/document.js:1286:17
    at validate (/Users/alanh/test2/auth/server/node_modules/mongoose/lib/schematype.js:705:7)
    at /Users/alanh/test2/auth/server/node_modules/mongoose/lib/schematype.js:742:9
    at Array.forEach (native)
    at SchemaString.SchemaType.doValidate (/Users/alanh/test2/auth/server/node_modules/mongoose/lib/schematype.js:710:19)
    at /Users/alanh/test2/auth/server/node_modules/mongoose/lib/document.js:1284:9
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

但如果我将firstName的要求更改为false,那么它可以正常工作。导致此错误的原因是什么?如何让它工作以便我可以firstName

0 个答案:

没有答案