1. 程式人生 > >Mongoose使用populate進行多表巢狀及深層巢狀查詢功能

Mongoose使用populate進行多表巢狀及深層巢狀查詢功能

mongoose populate 文件欄位說明

  • path «Object|String» 需要做表關聯的欄位路徑,或者包含所有引數的物件
  • [select] «Object|String» 表關聯查詢要選擇的欄位
  • [model] «Model» 表關聯的 model 。如果沒有指定,將以 Schema 中 ref 欄位為名稱查詢 model 進行關聯。
  • [match] «Object» population 查詢的條件
  • [options] «Object» population 查詢的選項 (sort 等)

首先,進入正題,我們定義三個Schema

auditOpinion = new Schema({
    drId: { type: Schema.ObjectId, ref: 'drFile' },
    cityId: Schema.ObjectId,
    remark:String
});

drFile = new Schema({
    name: { type: String, required: true, unique: true },
    pwd: String,
    cityId: { type: Schema.ObjectId, ref: 'cityFile' }
});

cityFile = new Schema({
    name: String
});

表auditOpinion的drId屬性指定表drFile的_id,表drFile的屬性cityId指定表cityFile的_id。find()對應auditOpinion表對篩選條件,這是一種巢狀關聯的關係。

查詢auditOpinion表的資料,並同時返回對應的sales表的資料,可以使用下面的方法:

auditOpinion.find().populate('drId', '_id name pwd cityId').exec(function(err, data) {
  if(err)console.log(err)
console.log(data)
});

返回的結果中除了auditOpinion表的資料外,還會包含drFile中_id,name,pwd,cityId四個屬性的值。但是cityId屬性的值是以ObjectId

的形式顯示的,如果想知道cityId對應表的其它值,則需要再次巢狀populate。程式碼如下

auditOpinion
        .find() //對應結果查詢
        .populate({
          path: 'drId', //對應auditOpinion表 設定欄位
          populate: {
            //相當於then,在巢狀查詢後,再在drFile表中根據cityId欄位對cityFile表進行關聯查詢
            path: 'cityId',
          }
        })

如果auditOpinion表中還存在其它ObjectId型別的欄位,則可以在populate方法後面繼續追加populate,使用方法相同

注意:如果在定義欄位型別的時候,沒有加上ref:"表名",則需要在使用populate的時候,增加一個model 指向對應的表,這樣才能正確查詢出結果,如下:

auditOpinion
        .find() //對應結果查詢
        .populate({
          path: 'dr_id', //對應auditOpinion表 設定欄位
        })
        .populate({
          //一張表可聯合多個表字段,根據auditOpinion中的欄位cityId對cityFile表進行關聯查詢
          path: 'cityId',
          model:'cityFile'//沒有新增ref路徑,則需要指向
        })

mongoose 傳送門 

https://cn.mongoosedoc.top/docs/api.html#query_Query-populate

https://cn.mongoosedoc.top/docs/populate.html