【问题标题】:How to implement inner join in mongoose如何在猫鼬中实现内连接
【发布时间】:2020-05-22 00:57:42
【问题描述】:

问题: 我想为具有动态参考和直接参考另一个模型的模型实现猫鼬的内部连接。请参考下面的示例架构和模型。

const schema1 = mongoose.schema({
   on: {
      type: Schema.Types.ObjectId,
      required: true,
      refPath: 'onModel'
   },
   onModel: {
      type: String,
      required: true,
      enum: ['Model2', 'Model3']
   },
   company: {
      type: Schema.Types.ObjectId,
      ref: 'Company'
   }
});

const Model1 = mongoose.model('Model1', schema1);


const schema2 = mongoose.schema({
   name: {
      type: String,
      maxlength: 100
   },
   email: {
      type: String,
      maxlength: 100
   }
});
const Model2 = mongoose.model('Model2', schema2);

const schema3 = mongoose.schema({
   name: {
      type: String,
      maxlength: 100
   },
   email: {
      type: String,
      maxlength: 100
   }
});
const Model3 = mongoose.model('Model3', schema3);

const companySchema = mongoose.schema({
   companyName: {
     type: String,
     maxlength: 100
   }
});
const company = mongoose.model('Company', companySchema);

const res = await models.Model1
            .find()
            .populate({
              path: 'on',
              match: {
                'name': keyword
              }
             })
            .populate({
              path: 'company',
              match: {
               'companyName': keyword
              }
            });

上面的 find 会返回文档,即使 on 并且 company 返回 null 值(因为 mongoose populate 默认实现了左连接)。

预期结果:我想从模型 1 中获取文档,前提是它与模型 2 或模型 3 中的名称字段或公司模型中的公司名称字段匹配的关键字。

如何做到这一点?非常感谢您的帮助。

【问题讨论】:

    标签: mongodb mongoose nosql inner-join


    【解决方案1】:

    1.让我们更新“模型 1”的架构,如下所示:-

        const schema1=mongoose.schema( {
            ref: {
                kind: String, // <-- This will store the Model Name (Model2 or Model3) when you execute the insert query.
                item: {
                    type: mongoose.Schema.Types.ObjectId, // <-- This will store the Reference ID of another table (Model2 OR Model3)
                    refPath: 'ref.kind', fields: String,
                }
                ,
            }
            , company: {
                type: Schema.Types.ObjectId, ref: 'Company'
            }
        });
    
    1. 保持 Model2Model3Company 的模式不变。此处无需进行任何更改。

    2. 当你想找到时:-

      await models.Model1.find().populate({ path: 'ref.item' });
      
    3. 就是这样。这应该有效。

    【讨论】:

    • 它会帮助我实现内部连接吗?请澄清。
    • 但是为什么它返回null。您提到了 required true,因此这意味着记录将存在于您的数据库中,并且您将其用作参考。
    • 它返回 null 因为这个条件失败 -> match: { 'name': keyword}
    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2022-01-26
    相关资源
    最近更新 更多