【问题标题】:How to get the parent of a schema in Mongoose?如何在 Mongoose 中获取模式的父级?
【发布时间】: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


    【解决方案1】:

    Mongo 没有父母,您需要在对象中使用聚合或创建对另一个集合的引用。

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

    【讨论】:

    • 问题是我已经在使用子文档,检查我的代码示例。
    【解决方案2】:

    其实this.parent().id起作用了:

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

    【讨论】:

      【解决方案3】:
      // 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-31
        • 2011-10-20
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多