猫鼬:从另一个子文档和总体引用一个子文档

时间:2018-07-03 05:31:06

标签: node.js mongodb mongoose mongoose-populate

我有一个名为 school 的文档模型,该模型又有两个子文档:

  1. 学生
  2. 课程

每个学生都属于一个班级。

var classSchema = new Schema({
	name: {type : String}
});

var studentSchema = new Schema({
	name : {type : String, required:true},
	class: { type: ObjectId, ref: 'Institute.classes' },
});

var schoolSchema = new Schema({
	name : {type : String, required:true},
	students : [studentSchema],
	classes : [classSchema]
});

var School = mongoose.model('School', schoolSchema);

现在,当我要招收学生时,我也想填充班级。我这样做是:

var school_id = req.params.school_id;
var student_id = req.params.student_id;

School
    .findOne({'_id': school_id, 'students._id': student_id})
    .populate({path: 'students.class'})
    .exec(function (err, data) {
        done(err, data);
    });

执行此操作时,出现以下错误:

"message": "Schema hasn't been registered for model \"School.classes\".\nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"

是否可以从另一个子文档中填充一个子文档? 任何帮助表示赞赏。谢谢:)

0 个答案:

没有答案