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

Node.js 如何在Mongoose中获取模式的父级?,node.js,mongoose,mongoose-schema,Node.js,Mongoose,Mongoose Schema,我正在编写一个Node.js应用程序,它使用Mongoose作为ORM 我有一个称为事件的模型和一个称为参与者的模式,它作为子文档存储在我的事件模式中。问题是,我需要实现一个应该访问父级数据的方法。而且没有关于这方面的文档(或者我找不到任何文档)。如何从父对象的子对象访问父对象的数据 我见过几次$parent的用法,但它对我不起作用。此外,我还使用了this.parent(),但这会导致RangeError:超出了最大调用堆栈大小(以我为例) 以下是我的代码示例: const Participa

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

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

我见过几次
$parent
的用法,但它对我不起作用。此外,我还使用了
this.parent()
,但这会导致
RangeError:超出了最大调用堆栈大小(以我为例)

以下是我的代码示例:

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

Mongo没有父对象,您需要在对象中使用聚合或创建对其他集合的引用

或者您可以使用mongoose子文档,请参阅文档:

实际上
this.parent().id
worked:

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

问题是我已经在使用子文档了,请检查我的代码示例。
// creating schemas
const ParticipantSchema = mongoose.Schema({});
const EventSchema = mongoose.Schema({
    title: {type: String, default: 'New event'},
    applications: {type: [Participant], default: []},
});

// creating models
const EventModel = mongoose.model('Event', EventSchema);
const ParticipantModel = mongoose.model('Participant', ParticipantSchema);

// creating instances
const event = new EventModel();
conts participant = new ParticipantModel();

// adding participant to event
event.applications.push(participant);

//accessing event title from participant. (parent data from child object)
const child = event.applications[0];
child.parent() // 'New event'