如何 link 在 mongo 中将一个模型转换为另一个模型

How to link one model to other in mongo

如何在 MongoDB 中建立关系。我有两个模式,事件和预订。

Events: {
 title: String,
 bookings: Array
}

Bookings; {
 title: String
}

在一次活动中,我有多个预订。我该如何注册?

mongoose.model('EventSchema', {
  title: String,
  bookings: Array
});

mongoose.model('BookingSchema', {
  title: String
});

所以我会:

Events: {
 title: 'MyEvent',
 bookings: [
  {eventone}
  {eventtwo}
  etc..
 ]
}

因此,请为您的活动模式提供一系列预订参考

mongoose.model('EventSchema', {
    title: String,
    bookings: [{
        type: ObjectId,
        ref: 'booking'
    }]
});

mongoose.model('BookingSchema', {
  title: String
});

然后在插入预订时获取结果 _id 并推送到事件数组

return EventModel
.findOneAndUpdate( query,
    {   $push: {
            bookings : currBooking_id
        }
    }
);