如何让猫鼬架构的家长吗?
我正在写使用猫鼬作为一个ORM一个Node.js应用程式。
我有一个模型,称为事件,以及一个架构,称为参与者,这是存储在我的事件模式作为一个子文档内。问题是,我需要实现应该访问父的数据的方法。而且也没有关于文档(或者我找不到任何)。我怎样才能从它的儿童获得父母的资料?
我见过$parent
几次的使用,但它并没有为我工作。此外,我已经播种this.parent()
的使用,但这会导致RangeError: Maximum call stack size exceeded
我的例子。
这里是我的代码示例:
const Participant = mongoose.Schema({
// description
});
const eventSchema = mongoose.Schema({
applications: [Participant],
// description
});
const Event = mongoose.model('Event', eventSchema);
Participant.virtual('url').get(function url() {
// the next line causes a crash with 'Cannot get "id" of undefined'
return `/${this.$parent.id}/participants/${this.id}`; // what should I do instead?
});
回答如下:
其实this.parent().id
工作:
Participant.virtual('url').get(function url() {
return `/${this.parent().id}/participants/${this.id}`;
});
如何让猫鼬架构的家长吗?
我正在写使用猫鼬作为一个ORM一个Node.js应用程式。
我有一个模型,称为事件,以及一个架构,称为参与者,这是存储在我的事件模式作为一个子文档内。问题是,我需要实现应该访问父的数据的方法。而且也没有关于文档(或者我找不到任何)。我怎样才能从它的儿童获得父母的资料?
我见过$parent
几次的使用,但它并没有为我工作。此外,我已经播种this.parent()
的使用,但这会导致RangeError: Maximum call stack size exceeded
我的例子。
这里是我的代码示例:
const Participant = mongoose.Schema({
// description
});
const eventSchema = mongoose.Schema({
applications: [Participant],
// description
});
const Event = mongoose.model('Event', eventSchema);
Participant.virtual('url').get(function url() {
// the next line causes a crash with 'Cannot get "id" of undefined'
return `/${this.$parent.id}/participants/${this.id}`; // what should I do instead?
});
回答如下:
其实this.parent().id
工作:
Participant.virtual('url').get(function url() {
return `/${this.parent().id}/participants/${this.id}`;
});