首页 文章

mongoose填充不填充数组

提问于
浏览
6

我面临的问题是mongoose查询没有填充数组类型 .

这是学院架构

'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.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的教师数组 .

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

1 回答

  • 2

    首先,您需要稍微更改模型,如 teachers 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);
        });
    };
    

    然后,将您的populate参数更改为 teachers.teacher . 它会工作

相关问题