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

标签 node.js mongoose mongoose-schema

我正在编写一个 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/

相关文章:

json - 在nodejs中将yaml文件转换为json

javascript - 如何在html页面或jade页面中显示mongoose结果

javascript - mongoose - 如何在 getter 中获取对象而不是对象引用?

node.js - 在 Jest 中创建 IncomingMessage 测试虚拟机

node.js - ".then is not a function"来自一个非常简单的查询程序

mysql - Heroku 和 NodeJs - MySql 连接丢失 : The server closed the connection

javascript - 我的应用程序不会更新数组中的值(Mongoose)

node.js - Handlebars 模板引擎循环问题

javascript - 如何以编程方式填充 Mongoose 模型字段?

node.js - Mongoose SchemaTypes 语法 : Array of ObjectIds