猫鼬模式ObjectID的数据透视表

时间:2019-03-28 13:36:49

标签: node.js mongodb mongoose pivot schema

我具有以下列表架构:

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'
    }],
});

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

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

1 个答案:

答案 0 :(得分:0)

我知道了。

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')时,您将从项目文档和附加列(数量)中获取所有内容

相关问题