2015-05-04 170 views
4

我正面臨一個問題,即貓鼬查詢不填充數組類型。貓鼬填充不填充數組

這裏是學院的模式

'use strict'; 

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var InstituteSchema = new Schema({ 
    name: String, 
    address: String, 
    city: String, 
    country: String, 
    zip: String, 
    owner: { type: mongoose.Schema.ObjectId, ref: 'User' }, 
    teachers: [{type: mongoose.Schema.ObjectId, ref: 'Teacher'}], 
    categories: [String], 
    created : { type : Date, default : Date.now } 
}); 

module.exports = mongoose.model('Institute', InstituteSchema); 

這裏是老師架構

'use strict'; 

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var TeacherSchema = new Schema({ 
    education: [{degree: String, instituteName: String}], 
    dob: Date, 
    photoUrl: String, 
    phoneNumber: String, 
    owner: {type: mongoose.Schema.ObjectId, ref: 'User'}, 
    institutes: [{type: mongoose.Schema.ObjectId, ref: 'Institute'}], 
    subjects: [{type: mongoose.Schema.ObjectId, ref: 'Subject'}], 
    created : { type : Date, default : Date.now } 
}) 

module.exports = mongoose.model('Teacher', TeacherSchema); 

這裏是一個查詢由所有者ID研究所

exports.mine = function (req, res, next) { 
    var ObjectId = mongoose.Types.ObjectId; 
    var userId = new ObjectId(req.user._id); 
    Institute.find({ 
     owner: userId 
    }).populate('teachers').exec(function (err, institute) { 
     if (err) return next(err); 
     if (!institute) return res.json(401); 
     res.json(institute); 
    }); 
}; 

我從看到的方法db那個研究所有老師加了

db.institutes.find(); 
{ 
    "_id" : ObjectId("554719a9f5be11c6d4369264"), 
    "owner" : ObjectId("5547199bf5be11c6d4369263"), 
    "country" : "USA", 
    "name" : "Raghvendra Singh", 
    "address" : "38589 Royal Ann Cmn", 
    "city" : "Fremont", 
    "zip" : "94536", 
    "created" : ISODate("2015-05-04T07:03:05.569Z"), 
    "categories" : [ "IIT", "Medical" ], 
    "teachers" : [ ObjectId("55471965f5be11c6d436925f") ], 
    "__v" : 3 
} 

但不知何故查詢方法不填充教師集合。奇怪的是,我甚至沒有收到對象id的集合,它返回並建立了空的老師數組。

而且,當我從方法調用中刪除.populate('teachers')時,它確實會返回帶有對象標識的教師數組。

我看着文檔,我看不到我做錯了什麼。

+0

''Teachers''文件在調用'mine'函數之前至少需要加載一次,才能使用Mongoose註冊模型。在你調用該函數之前,你是否在某個地方加載了該模塊? –

+0

我有「var Teacher = require('../ teacher/teacher.model.js');」在具有排雷功能的文件的開頭。 @BrianShamblen就是你的意思? –

+0

是的......一切*看起來*正確。我唯一要檢查的其他事情是驗證存儲在'teachers'數組中的ObjectId實際上是否參考了教師集合中的有效值。除此之外,我沒有看到任何明顯的。 –

回答

1

首先,您需要將教師 feild中的模型略作修改。

teachers: [ { teacher: { type: Schema.ObjectId, ref: "Teacher" } } ] 

exports.mine = function (req, res, next) { 
    var ObjectId = mongoose.Types.ObjectId; 
    var userId = new ObjectId(req.user._id); 
    Institute.find({ 
     owner: userId 
    }).populate('**teachers.teacher**').exec(function (err, institute) { 
     if (err) return next(err); 
     if (!institute) return res.json(401); 
     res.json(institute); 
    }); 
}; 

然後,你填入參數更改爲teachers.teacher。它將起作用