如何在mongo中将一个模型链接到另一个模型

时间:2015-11-22 02:22:35

标签: mongodb mongoose nosql

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

$config = [
   'scraper' => [
        'class' => 'app\models\Scraper',
        '_pageSize' => 10,
        '_client' =>  [  //not working. can not instantiate this property as an object
            'class' => 'Goutte\Client'
        ],
   ],
   //... 
]

有一次我有几次预订。我该如何注册?

Events: {
 title: String,
 bookings: Array
}

Bookings; {
 title: String
}

所以我会:

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

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

1 个答案:

答案 0 :(得分:0)

因此,请为您的事件架构提供一个参考预订

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

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

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

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