【发布时间】:2017-08-24 17:10:30
【问题描述】:
我正在尝试返回特定的状态代码,例如 409 冲突。我用过Model#save docs
编辑:我不是要解决这个错误,这是故意的。
根据文档,回调中有三个参数:err、product 和 numAffected。
编辑:我写错了这段代码,我编辑了。不管怎样,我从 Ryan 那里得到了很好的回答。
app.post('/skill', (req, res) => {
const skill = new Skill({some_duplicate_object});
skill.save((err, product, numAffected) => {
console.log("Error: ", err);
});
不是我的 console.log,在 Mocha 测试 cli 中,我收到一个错误:
(node:19760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): ValidationError: Path `name` is required.
通过玩弄运气,我做到了:这不在 mongoose 文档中,这是我写这篇文章的主要原因。
app.post('/skill', (req, res) => {
const skill = new Skill({});
skill.save()
.then((err, product, numAffected) => {
console.log("Nothing displayed here");
}, (err) => {
console.log(err.errors);
});
即使这不在文档中,它也会显示我想要的错误。作为一个真正尝试更多使用官方文档的人,我发现很难理解到底发生了什么。为什么这会起作用?如果它在文档中,这些信息会在哪里?
{ name:
{ MongooseError: Path `name` is required.
at ValidatorError (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/error/validator.js:24:11)
at validate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:706:13)
at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:752:11
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:712:19)
at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/document.js:1408:9
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Path `name` is required.',
name: 'ValidatorError',
properties:
{ type: 'required',
message: 'Path `{PATH}` is required.',
validator: [Function],
path: 'name',
value: undefined },
kind: 'required',
path: 'name',
value: undefined,
reason: undefined } }
额外信息:
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^2.4.5",
"request": "^2.81.0",
"supertest": "^3.0.0"
},
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"mongoose": "^4.9.2"
}
【问题讨论】:
-
您在 Mocha 中看到了错误,因为在
catch()中没有错误。你需要skill.save().then(function(result){}).catch(function(err){}) -
看起来
skill也设置了一些验证,我抱怨您没有传递PATH值的错误。 -
您已在架构中设置了所需的名称字段,因此当您尝试保存文档时出现验证错误,因为没有提供名称
标签: node.js express mongoose mocha.js chai