【问题标题】:Pivot table for Mongoose Schema ObjectIDMongoose Schema ObjectID 的数据透视表
【发布时间】:2019-08-19 07:21:48
【问题描述】:

我有以下列表架构:

const ListSchema = mongoose.Schema({
    title: { type: String, required: true, max: 100 },
    items: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Item'
    }],
});

当我用项目填充它时,一切正常。但是,我想为列表中的每个项目添加一列,因此我更改了架构:

const ListSchema = mongoose.Schema({
    title: { type: String, required: true, max: 100 },
    items: [{
      item: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Item'
      },
      quantity: 'String'
    }],
});

不幸的是,populate 方法不适用于上述方法。

对于关系数据库,我会使用数据透视表来保存列表 ID、项目 ID 和数量,但我真的不知道 MongoDB 如何处理此类情况。欢迎提出任何建议。

【问题讨论】:

  • 您应该将 quantity 字段保留在 items 集合中。
  • 不,我是说你应该把它放在 items 集合中,而不是像你在 items: [{ item: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' }, quantity: 'String' }] 中所做的那样放在对象数组中
  • 即使我像这样添加它items: [{ item: { type: mongoose.Schema.Types.ObjectId, ref: 'Item', quantity: 'String' }, }], 它仍然不会将数量值添加到数据库中
  • 你能展示你的items收藏吗
  • const ItemSchema = mongoose.Schema({ name: { type: String, required: true, min: 1 }, created_at: { type: Date, default: Date.now }, });

标签: node.js mongodb mongoose pivot schema


【解决方案1】:

我想通了。

const ListSchema = mongoose.Schema({
  title: { type: String, required: true, max: 100 },
  items: [{
      type: mongoose.Schema.Types.Mixed, ref: 'Item', quantity: 'String'
  }],
});

基本上,我已将项目的架构类型从 mongoose.Schema.Types.ObjectId 更改为 mongoose.Schema.Types.Mixed。

这样,当您.populate('items._id') 时,您将从项目文档和您的附加列(数量)中获取所有内容

【讨论】:

    猜你喜欢
    • 2015-11-26
    • 2019-12-09
    • 2013-02-06
    • 2018-04-10
    • 2016-06-13
    • 2021-03-03
    • 2012-08-20
    • 2015-05-02
    • 2017-11-22
    相关资源
    最近更新 更多