【发布时间】:2018-10-27 00:10:16
【问题描述】:
我正在编写一个使用 Mongoose 作为 ORM 的 Node.js 应用程序。
我有一个名为 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?
});
【问题讨论】:
标签: node.js mongoose mongoose-schema