mongoose填充对子文档的引用

我找不到任何回应我的问题。 可能也是一个search问题,但会感谢一些帮助。 我有以下模型:

var ChildSchema = new Schema ({ 'name': string }); var ClassSchema = new Schema ({ 'name': string, 'children': [ChildSchema] }); 

我只是宣布了一个class的模型。

 mongoose.model ('Class', ClassSchema); 

然后我有另一个模型:

 var TeacherSchema = new Schema ({ 'name': string, 'favorite': {type: ObjectId, ref: 'Class.children'} // a child from class children 'least': {type: ObjectId, ref: 'Class.children'} // same as above }); 

有了相关型号:

 mongoose.model ('Teacher', TeacherSchema); 

我正在尝试通过ID检索教师并获取填充的孩子名称:

 Teacher.findbyId (teacherId).populate (favorite least)... 

这似乎并不奏效。 这种build模是否正确? 这可能吗?

(我知道我的例子可能不是在政治上是正确的,所以请原谅我…)

编辑这是在项目中的东西的反映。 我知道,孩子们可以build模为单独收集,但在我的项目中,我更愿意将它们作为embedded式文档(由于各种原因)。 每个孩子在被推入子数组时都会得到一个_id,并保存该类。 教师需要在“喜欢”和“至less”的阶级中指出一个单独的孩子,即保留该孩子的某个孩子。

答案似乎是:不可行。 github.com/Automattic/mongoose/issues/2772另外 – 找不到合适的插件。

我有一个类似的问题。 至less如果你有一个引用返回从孩子的类,这可以工作:

 var TeacherSchema = new Schema ({ 'class': {type: ObjectId, ref: 'Class'} 'name': string, '_favorite': {type: ObjectId, ref: 'Class.children'} // a child from class children '_least': {type: ObjectId, ref: 'Class.children'} // same as above }); TeacherSchema.virtual('favorite').get(function() { return this.class.children.id(this._favorite); }); TeacherSchema.virtual('favorite').set(function(favorite) { this._favorite = favorite; }); TeacherSchema.virtual('least').get(function() { return this.class.children.id(this._least); }); TeacherSchema.virtual('least').set(function(least) { this._least = least; }); TeacherSchema.set('toJSON', { getters: true, virtuals: true }); 

这只要一个老师只有一个class级就可以工作。