gpt4 book ai didi

node.js - 如何在 Mongoose 中获取模式的父级?

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:30 25 4
gpt4 key购买 nike

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

我有一个模型(称为“事件”)和一个架构(称为“参与者”),它作为子文档存储在我的“事件”架构中。问题是,我需要实现一个应该访问父级数据的方法。并且没有关于此的文档(或者我找不到任何文档)。如何从子级访问父级的数据?

我见过几次 $parent 的用法,但它对我不起作用。另外,我还使用了 this.parent(),但在我的示例中,这会导致 RangeError: Maximum call stack size gone

这是我的代码示例:

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

关于node.js - 如何在 Mongoose 中获取模式的父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50379335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com