2017-09-05 80 views
-2

我有一個是寫在的NodeJS和MongoDB一個web應用程序,我有以下兩種模式搜索查詢和填充的數據

var TeacherSchema = new Schema({ 
     school_id:[{type: Schema.Types.ObjectId, ref: 'School'}], 
     name: String, 
     subjects: [{type: Schema.Types.ObjectId, ref: 'Subject'}], 
     }); 


var SubjectSchema = new Schema({ 
    title : String, 
    school_id:[{type: Schema.Types.ObjectId, ref: 'School'}] 
    }); 

我寫的搜索拋出教師或學科

的API
router.get("/field-teacher-subject", function (req, res) { 
var school_id= req.query.schoolId; 
Subject.find(school_id:'school_id,function (err, subjects) { 
    if (err) { 
     console.log(err); 
     res.json({status: "error", message: err.message}); 
    } else { 
     var sub_array=[]; 
     for(var q in subjects){ 
      sub_array.push(subjects[q]._id); 
     } 
     Teacher.find({subjects:{$in :sub_array }},{first_name:true, father_name:true, last_name : true, subjects:true}).populate('subjects') 
      .exec(function(tech) { 
       console.log("hello: "); 
       var subjeto = []; 
       if(tech){ 
        for(var p in tech){ 
         subjeto.push(tech[p].subjects); 
        } 
       } 
       res.json({status: "success", message: "subjects returned", 
      items: tech}); 
      }).catch(function(err){ 
       if(err){ 
        res.json({status:"error", 
         message:"error occurred"+err.message}); 
        return; 
       } 
      }); 
    } 
}).limit(parseInt(req.query.max)); 
}); 

當我搜索一個名字返回null, 什麼是解決這一

+0

搜索一個名字在哪裏?我在這裏沒有看到任何與名字匹配的東西。哪個名字?老師的名字?不是很清楚你在問什麼。 –

+0

教師姓名或科目名稱 – motchezz

回答

1

很難知道你問什麼是最好的方式,但你的代碼有幾個錯誤秒。我們來清理你的代碼吧?

router.get("/field-teacher-subject", function (req, res) { 
    // get subjects 
    Subject 
     .find({ school_id: req.query.schoolId }) // 1st argument is an object 
     .limit(parseInt(req.query.max))    // should go before 
     .exec(function (err, subjects) {   // use .exec() 
      if (err) { 
       console.log(err); 
       return res.json({ status: "error", message: err.message }); 
      } 
      // get subject IDs 
      var sub_array = subjects.map(function (subject) { return subject._id; }); 
      // get teachers assigned to subjects 
      Teacher 
       .find({ subjects: { $in: sub_array }}) 
       .select('first_name father_name last_name subjects') 
       .populate('subjects') 
       .exec(function(err, teachers) {  // 1st argument is an error 
        if (err) { 
         console.log(err); 
         return res.json({status: "error", message: err.message }); 
        } 
        var subjeto = teachers.map(function (teacher) { return teacher.subjects; }); 

        res.json({status: "success", message: "subjects returned", items: teachers }); 
       }); 
    }); 
}); 

相關鏈接:

  • 參見如何使用.limit().exec()doc第三個例子。

  • .map()

  • 您嘗試使用.exec().then().catch()在你的第二個查詢