【发布时间】:2020-08-25 13:38:23
【问题描述】:
每次我尝试检查我的 if 条件 (project== null) 时都会收到 mongoose 错误。请看下面的代码:
var IssueSchema= new Schema ({
issue_description: {
type: String,
min: 5,
max: 500,
required: true
},
issue_status: {
type: String,
min: 5,
max: 255,
default: "Open"
},
issue_priority: {
type: String,
min: 5,
max: 255
},
deadline:{
type: Date
},
},
{timestamps:true});
var Project= new Schema ({
name: {
type: String,
required: true,
min: 5,
max: 255
},
description: {
type: String,
min: 5,
max: 500
},
status: {
type: String,
min: 5,
max: 255
},
priority: {
type: String,
min: 5,
max: 255
},
progress: {
type: String,
min: 5,
max: 255
} ,
issues: [IssueSchema],
risks: [RiskSchema],
_user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {timestamps:true});
代码:
控制器
Project.findById({_id:req.params.projectId}, (err,project) => {
console.log(project);
if (project == null) {
err= new ErrorHandler(404, "Project not found");
return next (err);
}
else {
project.issues.push(req.body);
project.save();
res.status(200).send('Issue created');}
}
)};
路由器
projectRouter.route ('/:projectId/issues')
.post(issueController.createIssue)
如果我输入正确的投影,它会正常工作。但是我想处理指定的 projectID 不存在的情况。当我在 URL 参数中输入一些随机 projectID 时,它会抛出:UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "123" at path "_id" for model "Project"。
任何想法我做错了什么?
【问题讨论】:
标签: mongodb express mongoose mongodb-query