我是猫鼬和表达的新手。试图找到我问题的答案,但是没有运气。我有以下架构:
var Schema = mongoose.Schema;
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
} ,
_user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
module.exports= mongoose.model('Project', Project);
var Schema = mongoose.Schema;
var IssueSchema= new Schema ({
description: {
type: String,
min: 5,
max: 500,
required: true
},
status: {
type: String,
min: 5,
max: 255,
default: "Open"
},
priority: {
type: String,
min: 5,
max: 255
},
deadline:{
type: Date
},
_project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Project'
}
});
module.exports= mongoose.model('Issue', IssueSchema);
我正在为/ projectId / issues路由创建Issue中间件,并具有代码
const bodyParser = require('body-parser');
const Issue = require ('../models/Issue');
var Project = require ('../models/Project');
const { handleError,ErrorHandler } = require('../helpers/error');
exports.createIssue = (req, res,next) => {
Project.findById(req.params.id);
if (req.params.id!= null) {
console.log('Project found');
const {description, deadline, priority, status} = req.body;
var issue = new Issue({
description,
deadline,
status,
priority,
_project:req.params.id
});
issue.save();
res.status(200).send("Issue created!")}
else {
err = new Error('Project ' + req.params.id + ' not found');
err.status = 404;
return next(err);
}
};
并且它不起作用:(我想要实现的是在保存“问题”文档之前检查projecID是否存在。有关如何实现此操作的任何想法?
答案 0 :(得分:0)
您正在检查是否将id传递给params:
if (req.params.id!= null)
但是,这并不能告诉您是否存在与该ID相关的项目。您需要检查Project.findById(req.params.id)的返回值。像这样:
let result = Project.findById(req.params.id)
if(!result.length) console.log('No project found")
在这种情况下,我很确定result变量将是一个数组,但是它也可能是一个对象,因此console.log(result)看看得到了什么。然后在此基础上编写条件语句。
此外,如果要捕获任何错误,则需要使用try / catch块而不是if / else。
答案 1 :(得分:0)
Project.findById
接受参数为error
和document
的回调
Project.findById(req.params.id, (error, project) => {
console.log(project) // project will be null if not found.
// handle project !== null here
})