如何让猫鼬架构的家长吗?

问题描述 投票:2回答:3

我正在写使用猫鼬作为一个ORM一个Node.js应用程式。

我有一个模型,称为事件,以及一个架构,称为参与者,这是存储在我的事件模式作为一个子文档内。问题是,我需要实现应该访问父的数据的方法。而且也没有关于文档(或者我找不到任何)。我怎样才能从它的儿童获得父母的资料?

我见过$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
3个回答
1
投票

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

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

0
投票
// 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'

-1
投票

蒙戈没有了父母,你需要用聚集在你的对象,或者创建到另一个集合的引用。

或者你可以使用猫鼬子文档,请参阅文档:http://mongoosejs.com/docs/3.0.x/docs/subdocs.html

© www.soinside.com 2019 - 2024. All rights reserved.