mongoose填充不填充数组

我正面临着一个问题,即mongoose查询不填充数组types。

这是研究所架构

'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); 

这是Schema老师

 '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的集合,它返回并build立了空的老师数组。

当我从方法调用中删除.populate('teachers')时 ,它确实返回了带有对象id的老师数组。

我看了文档,我看不出我做错了什么。

首先,你需要稍微改变你的模型作为提到教师职业。

 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 。 它会工作