【问题标题】:Mongoose equivalent of JOIN ... WHEREMongoose 相当于 JOIN ... WHERE
【发布时间】:2020-05-11 17:35:03
【问题描述】:

我有两个模型

Opinion {
  _id: string;
  creator: string;
  teacher: ObjectId;
  text: string;
  date: Date;
}

Teacher {
  _id: string;
  name: string;
  isVerified: boolean;
}

我需要获得 3 个最新意见 WHERE { teacher.isVerified: true }

我试过了

    const newOpinions = await Opinion.find(
      null,
      "creator teacher text",
      {
        sort: {
          date: -1,
        },
      }).populate(
        {
          path: 'teacher',
          model: 'Teacher',
          select: 'name',
          match: {
            isVerified: true,
          },
        }
      ).limit(3);

但是(经过简短分析)它按设计工作 - 无论教师是否经过验证,我都会收到 3 个最新意见(在教师领域,如果未经验证,我会收到 null

任何人都可以尝试为我指出正确的方向吗?我想可能是Model.aggregate()

【问题讨论】:

    标签: javascript mongodb express mongoose non-relational-database


    【解决方案1】:

    这是一种方法。有了这个,您将首先过滤教师。也请咨询$lookup documentation

    Teacher.aggregate([{
      $match: { isVerified: true }
    }, {
      $lookup: {
        from: 'opinions' // assume you have collection named `opinions` for model `Opinion`,
        localField: '_id', // join teacher._id ...
        foreignField: 'teacher', // ... with opionion.teacher
        as: 'opinions'
      } // from here you well get verified teachers with embedded opinions, 
    // further stages are optional. We will modify the shape of output to be opinions only
    }, { 
      $unwind: '$opinions' // spread out opinions array into separate documents
    }, {
      $replaceRoot: '$opinions' // replace the root document with opinion only
    }])
    

    【讨论】:

      【解决方案2】:

      在mongodb中相当于join的是$lookup。一种猫鼬方法是使用填充,但您必须在模型中提供 ref 键

      用于查找用途 https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

      猫鼬参考

      Opinion {
        _id: string;
        creator: string;
        teacher: {
            type: Schema.Types.ObjectId, ref: 'Teacher'
        },
        text: string;
        date: Date;
      }
      
      Teacher {
        _id: string;
        name: string;
        isVerified: boolean;
      }
      

      $lookup 方法更加灵活和可定制

      【讨论】:

        猜你喜欢
        • 2014-06-23
        • 1970-01-01
        • 2016-07-20
        • 2020-02-13
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        相关资源
        最近更新 更多