我有一个带有必填字段name
的Food架构。出于某种原因,当我尝试使用create
函数(下面)创建一个食物项时,它会抛出一个ValidationError: Path 'name' is required
,即使我的对象确实有一个名称字段:
Food.create({
name: "milk",
daysUntilExpiration: 5
});
我的mongoose调试输出还显示它正在执行插入,并且保存的对象具有名称字段:
Mongoose: foods.insert({ name: 'milk', daysUntilExpiration: 5, _id: ObjectId("59608100cb0578165dd35de9"), __v: 0 })
另一方面,如果我创建一个新对象然后保存,它将按预期工作:
f = new Food({ name: "milk", daysUntilExpiration: 5 });
f.save() // no validation error!
为什么这种行为有所不同?我的印象是,create和new / save之间的差异纯粹是为了编程方便(e.g.想要在创建对象之后但在保存到数据库之前使用对象),但看起来我似乎#&# 39;我错了。
编辑:验证错误的堆栈跟踪:
ValidationError: Food validation failed: name: Path `name` is required.
at ValidationError.inspect (/Users/jess/herb/node_modules/mongoose/lib/error/validation.js:63:24)
at formatValue (util.js:352:36)
at inspect (util.js:186:10)
at exports.format (util.js:72:24)
at Console.log (console.js:43:37)
at tryCatcher (/Users/jess/herb/node_modules/bluebird/js/main/util.js:26:23)
at Promise._settlePromiseFromHandler (/Users/jess/herb/node_modules/bluebird/js/main/promise.js:507:31)
at Promise._settlePromiseAt (/Users/jess/herb/node_modules/bluebird/js/main/promise.js:581:18)
at Promise._settlePromises (/Users/jess/herb/node_modules/bluebird/js/main/promise.js:697:14)
at Async._drainQueue (/Users/jess/herb/node_modules/bluebird/js/main/async.js:123:16)
at Async._drainQueues (/Users/jess/herb/node_modules/bluebird/js/main/async.js:133:10)
at Immediate.Async.drainQueues (/Users/jess/herb/node_modules/bluebird/js/main/async.js:15:14)
at runCallback (timers.js:651:20)
at tryOnImmediate (timers.js:624:5)
at processImmediate [as _immediateCallback] (timers.js:596:5)
errors:
{ name:
{ MongooseError: Path `name` is required.
at ValidatorError (/Users/jess/herb/node_modules/mongoose/lib/error/validator.js:24:11)
at validate (/Users/jess/herb/node_modules/mongoose/lib/schematype.js:744:13)
at /Users/jess/herb/node_modules/mongoose/lib/schematype.js:790:11
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/Users/jess/herb/node_modules/mongoose/lib/schematype.js:750:19)
at /Users/jess/herb/node_modules/mongoose/lib/document.js:1462:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
message: 'Path `name` is required.',
name: 'ValidatorError',
properties: [Object],
kind: 'required',
path: 'name',
value: undefined,
reason: undefined } },
_message: 'Food validation failed',
name: 'ValidationError' }
编辑2:食物架构:
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 1,
max: 100
},
daysUntilExpiration: {
type: Number,
min: 0
}
});
module.exports = mongoose.model('Food', schema);