如何从一个项目获得所有事件?
当我搜索事件时,将其填充,并为事件带来所有引用数据,但是我想通过ID搜索项目,并在项目中获取下面的所有事件,但需要将其查找到获取事件的其他模式
我为此编写的代码是
router.get('/events/:section?', (req, res) => {
var sectionId = req.params.section
if (!sectionId) {
var find = Event.find({}).sort('dateStart')
} else {
var find = Event.find({section: sectionId}).sort('dateStart')
}
find.populate({
path: 'section',
populate: {
path: 'work',
model: 'Work',
populate: {
path: 'build',
model: 'Build',
populate: {
path: 'project',
model: 'Project'
}
}
}
}).exec((err, events) => {
if (err) {
res.json({ success: false, message: err })
} else {
if (!events) {
res.json({ success: false, message: 'No se encontraron eventos' })
} else {
res.json({ success: true, events: events })
}
}
})
})
这是我的模式
var ProjectSchema = new Schema({
name: { type: String, required: true, validate: nameValidators },
createdBy: { type: String },
created_at: { type: Date, default: Date.now() },
comments: [
{
comment: { type: String, validate: commentValidators },
commentator: { type: String }
}
]
})
module.exports = mongoose.model('Project', ProjectSchema)
var BuildSchema = new Schema({
name: { type: String, required: true, validate: nameValidators },
project: { type: mongoose.Schema.Types.ObjectId, ref: 'Project' },
createdBy: { type: String },
created_at: { type: Date, default: Date.now() }
})
module.exports = mongoose.model('Build', BuildSchema)
var WorkSchema = new Schema({
name: { type: String, required: true, validate: nameValidators },
build: { type: mongoose.Schema.Types.ObjectId, ref: 'Build' },
createdBy: { type: String },
created_at: { type: Date, default: Date.now() }
})
module.exports = mongoose.model('Work', WorkSchema)
var SectionSchema = new Schema({
name: { type: String, required: true, validate: nameValidators },
work: { type: mongoose.Schema.Types.ObjectId, ref: 'Work' },
createdBy: { type: String },
created_at: { type: Date, default: Date.now() }
})
module.exports = mongoose.model('Section', SectionSchema)
var EventSchema = new Schema({
name: { type: String, required: true, validate: nameValidators },
section: { type: mongoose.Schema.Types.ObjectId, ref: 'Section' },
dateStart: { type: String, required: true },
dateFinish: { type: String, required: true },
realStart: { type: String },
realFinish: { type: String },
isBegin: { type: Boolean, default: false },
isCompleted: { type: Boolean, default: false },
createdBy: { type: String },
created_at: { type: Date, default: Date.now() },
comments: [
{
comment: { type: String, validate: commentValidators },
commentator: { type: String }
}
]
})
module.exports = mongoose.model('Event', EventSchema)