猫鼬填充对子文档的引用 [英] mongoose populate reference to subdocument

查看:59
本文介绍了猫鼬填充对子文档的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到对我的问题的任何回复.可能也是搜索问题,但希望能有所帮助. 我有以下模型:

I could not find any response to my issue. Probably also a search issue, but would appreciate some help. I have the following model:

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

我只声明了一个课堂模型.

I have only declared a model for 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检索老师并填充孩子的姓名:

I am trying to retrieve a teacher by ID and get the children name populated:

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

这似乎不起作用.这个模型正确吗?这可能吗?

This does not seem to work. Is this modelling correct? Is this possible?

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

(I am aware that my example might not be politically correct, so please forgive me...)

编辑 这反映了项目中的某些内容.我知道可以将这些子项建模为单独的集合,但是在我的项目中,我更喜欢将它们保留为嵌入式文档(出于各种原因). 当每个子级被推入children数组并保存类时,确实会获得一个_id.老师需要以最喜欢"和最少"的方式指向班级中的一个孩子,即保持该孩子的_id.

EDIT This is a reflection of something in project. I am aware that the children can be modelled as seperate collection, but in my project, I prefer to keep them as embedded documents (for various reasons). Each child does get an _id when pushed into the children array and class is saved. The teacher needs to point to a single child in a class in "favorite" and in "least", i.e. to keep the _id of that child.

推荐答案

我有一个类似的问题.至少如果您有一个从Child返回到Class的引用,则可以这样做:

I have a similar problem. At least if you have a reference back to the Class from Child, this could work:

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

只要老师只有一堂课,这是可行的.

This works as long as a teacher has only 1 class.

这篇关于猫鼬填充对子文档的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆