簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z 相當於 JOIN ... WHERE

[英]Mongoose equivalent of JOIN … WHERE

我有兩個模型

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()

這是一種方法。 有了這個,您將首先過濾教師。 另請參閱$lookup文檔

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
}])

mongodb 中的 join 等價物是 $lookup。 mongoose 方法是使用填充,但您必須在 model 中提供參考密鑰

對於查找用法https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

Mongoose 參考

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM