首页 > 解决方案 > MongoDB - 我应该以哪种方式建立关系?

问题描述

我目前正在尝试使用 Node.js 和 MongoDB 来为我的婚礼构建一个应用程序。我目前正在为婚礼早餐做一个餐桌规划器,它就像一个 Trello 板。每位客人都是一件物品,每张餐桌就像一个 trello 列表。因此,在构建时,我们可以将客人从未分配的堆中拖放到特定的 trello 样式板上,这将为他们分配一个位置。

每张早餐桌可容纳多位客人,一位客人只能坐在一张桌子旁。我有点困惑是否在来宾模型中包含“表”作为外键,反之亦然。

将“表”作为外键让我可以轻松查询当前没有表的客人。另一方面,在“表”模型中将客人作为外键让我可以轻松查询尚未分配任何客人的表。

我需要执行上述两个查询才能更新 React 中的状态。

下面显示了我的 Guest 模式及其与表模型的关系:

const guestSchema = new mongoose.Schema({
  firstname: {
      type: String,
      required: 'Please provide the first name of the guest',
      trim: true
  },
  surname: {
      type: String,
      required: 'Please provide the surname of the guest',
      trim: true
  },
  attending: {
      type: String,
      default: 'Awaiting RSVP'
  },
  menu: {
      type: String,
      default: 'Awaiting RSVP'
  },
  allergies: {
      type: String,
      default: 'Awaiting RSVP'
  },
  table: {
      type: mongoose.Schema.ObjectId,
      ref: 'Table',
  }
});

const tableSchema = new mongoose.Schema({
  name: {
    type: String,
    required: 'Please provide the name of the table',
    trim: true
  },
  capacity: {
    type: Number,
    required: 'Please provide the capacity of the table',
  }
});

标签: mongodbdatabase-design

解决方案


我会将桌子编号存储在此人身上,尽管我不知道您会遇到任何问题。

在设计数据库时,孩子应该(通常)参考他们的父母,而不是相反。在我看来,桌子“拥有”坐在桌子旁的人(一对多关系),而不是拥有桌子的一部分的人,使桌子成为父级。

如果有人移动表,另一个好处是单点更新。您只需更新客人记录,而不是从一个表中删除并添加到另一个表中。

通常在建模决策中帮助我的是从更宏观的角度看待问题。想象一下创建一个关于人们居住地的数据库。您可能希望有人拥有街道地址属性和链接到州记录的字段,而州记录具有链接到国家/地区记录的字段。一旦你概括和扩大你的问题,通常会有一个更清晰的解决方案。

如果采用这种方法,则可以使用聚合来确定哪些表未满。

db.guests.aggregate([ {$group : { _id: '$tableId', seatsFilled : {$sum : 1}}} ])

推荐阅读