我正在尝试返回特定的状态代码,例如,409 Conflict . 我用了Model#save docs
编辑: I am not trying to solve the error, it is deliberate.
根据文档,回调有三个参数:err,product和numAffected .
EDIT: I wrote this code wrong and I edited. Either way, I got an excellent answer from 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.
通过玩耍和剪切运气,我这样做了: This is NOT in the mongoose docs and is my main reason for writing this post.
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"
}
2 回答
你的问题有两个问题,你得到的两个错误都告诉你到底出了什么问题 . 你的麻烦的根源是缺乏理解(不试图挑选你) . 这就像你是电子学的初学者一样,我告诉你,管子偏向不正确,你说"I don't understand" - 嗯,你需要了解管子然后因为我刚刚向你描述了电路的确切问题 .
1. Promise error -
UnhandledPromiseRejectionWarning: Unhandled promise rejection...
. 这不能说明 . 承诺是1)已解决或2)被拒绝 . 如果您拒绝"handle"被拒绝的案件,您将收到错误 . 处理被拒绝的承诺可能有以下两种方式之一:使用上述任一方案意味着您正确“处理”了承诺拒绝 .
2. Database validation -
Path 'name' is required.
. 这实际上意味着您有一个必需的路径,名为"name",这是必需的(意思是,它必须有一个值) . 所以看看你的代码很明显:通过在保存之前添加所有必需数据来解决此问题:
你没有处理承诺拒绝 .
改变这个:
对此:
当然会改变回调中发生的事情,无论你需要什么 .
有关未处理拒绝的更多常规信息,请参阅此答案: