如何在猫鼬中获取模式的父级?

ser*_*off 4 mongoose node.js mongoose-schema

我正在编写一个 Node.js 应用程序,它使用 Mongoose 作为 ORM。

我有一个名为 Event 的模型和一个名为 Participant 的模式,它作为子文档存储在我的 Event 模式中。问题是,我需要实现一个应该访问父数据的方法。并且没有关于此的文档(或者我找不到任何文档)。如何从其孩子访问父母的数据?

我见过$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?
});
Run Code Online (Sandbox Code Playgroud)

ser*_*off 5

实际this.parent().id工作:

Participant.virtual('url').get(function url() {
    return `/${this.parent().id}/participants/${this.id}`;
});
Run Code Online (Sandbox Code Playgroud)