在循环内找到猫鼬呼叫

时间:2018-10-17 13:55:24

标签: node.js mongodb mongoose

为简化我的问题,我有5个模型。 学生,老师,课程,订阅,考试 我想获取学生的饲料,每个学生都通过“订阅”模型连接到一些老师。 一个学生订阅一门课程,一个老师。

const subscriptionSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
createdAt: { type: Date, default: Date.now },
finishDate: { type: Date, required: true },
student:{ type: Schema.Types.ObjectId, ref: 'student' },
teacher:{ type: Schema.Types.ObjectId, ref: 'teacher' },
course:{ type: Schema.Types.ObjectId, ref: 'course' },
amount:Number,
details:String})

我想调用find()函数来查找“该学生的老师订阅的每项考试(在同一课程中)”

for example, 
Student S1 is subscribed to teacher T1 with course C1
Student S1 is subscribed to teacher T2 with course C2
Student S1 is subscribed to teacher T3 with course C1

我有一个函数返回S1的所有有效订阅。 我想查找S1老师发布的并且都在指定课程中的所有考试。

我想使用$ all:

module.exports.feed=(req,res)=>{
//TODO:get feed for this student
//first find subscriptions of the student
SubscriptionController.get_student_subscriptions(req,res,(err,value)=>{
    var teachers = [];
    value.forEach(v=>{
        teachers.push(v.teacher);
    })
    var feed = [];
    Exam.find({student:req.user.id , teacher: {$all : teachers} },(err,result)=>{
        handleRes(res,-1,ids)
    })
})}

,但很快就意识到它无法按我的意愿工作。 最佳解决方案是:如果我可以使用forEach()并在其中使用Exam.find()

0 个答案:

没有答案