簡體   English   中英

Mongoose 返回 null 查詢屬性引用

[英]Mongoose Returning null Reference of Property on Query

我在 Mongoose 中定義了兩個簡單模型,由兩個模式 Client 和 City 組成,我在 Client 中將屬性 city 定義為 ObjectId,ref: 'City',到目前為止一切順利。

如果我查詢一個客戶並且還想按城市的“省”屬性進行過濾,我會這樣做:

const client = await Client
    .find({ name: "Gérard" })
    .populate([{
        path: 'city',
        model: City,
        match: { province: 'BA' }
    }]);

而 output 就好了:

{
  "id": "627264e3ec261a883d42ead9",
  "name": "Gérard",
  "email": "gerard@depardieu.fr",
  "date": "1948-12-27",
  "active": true,
  "city": {
    "id": "627264e3ec261a883d42ead1",
    "name": "Buenos Aires",
    "province": "BA"
  }
}

但是,如果我輸入一個不存在的城市的省代碼:

const client = await Client
    .find({ name: "Gérard" })
    .populate([{
        path: 'city',
        model: City,
        match: { province: 'CA' }
    }]);

它返回給我這個:

{
  "id": "627264e3ec261a883d42ead9",
  "name": "Gérard",
  "email": "gerard@depardieu.fr",
  "date": "1948-12-27",
  "active": true,
  "city": null
}

在這種特定情況下,我不希望返回任何 Client 實例,而且我不知道如何使用 Mongoose 避免這種行為,例如,我從來不必擔心 Spring 數據的這種行為。

這里有人告訴我在我的代碼中做這樣的事情:

const client = await Client
    .find({ name: "Gérard" })
    .populate([{
        path: 'city',
        model: City,
        match: { province: 'CA' }
    }]);

if(client && client.city){

   return client; //or pass it to the response... whatever...
}

然而,假設這個查詢是在一個擁有數百萬客戶的集合上完成的,上面的代碼是一種資源浪費,我什至不會開始討論它有什么問題(好吧,你可以想象有多少客戶不在省內'CA' 數據庫服務器將發送到我的應用程序服務器只是為了被拒絕....)。

如果那個城市/省不匹配,我想要的是根本不返回任何客戶。

一個例子是模擬 SQL:

SELECT * FROM CLIENT JOIN CITY ON CITY.ID=CLIENT.CITY_ID WHERE CITY.PROVINCE = 'CA' 

一旦數據庫中唯一的客戶的省份 = 'BA',這里就沒有客戶返回。

那么,如何才能做到呢?

提前致謝。

我自己解決了它,我不得不將 go 與 Mongoose 結合使用聚合和查找。

const client = await Client.aggregate([
  { 
    $match: { name: "Gérard" } 
  },
  {
    $lookup: {
      from: City.collection.name,
      pipeline: [
        {
          $match: {
            province: 'BA'
          }
        }
      ], as: "city"
    }
  },
  {
     $unwind: "$city"
  },
  {
     $match: {
       city: { $ne: [] }
     }
   }
]);

預期結果:

{
  "id": "627264e3ec261a883d42ead9",
  "name": "Gérard",
  "email": "gerard@depardieu.fr",
  "date": "1948-12-27",
  "active": true,
  "city": {
    "id": "627264e3ec261a883d42ead1",
    "name": "Buenos Aires",
    "province": "BA"
  }
}

女巫還好,客戶名字“Gérard”住在“布宜諾斯艾利斯”,位於“BA”省。

另一方面:

const client = await Client.aggregate([
  { 
    $match: { name: "Gérard" } 
  },
  {
    $lookup: {
      from: City.collection.name,
      pipeline: [
        {
          $match: {
            province: 'CA'
          }
        }
      ], as: "city"
    }
  },
  {
     $unwind: "$city"
  },
  {
     $match: {
       city: { $ne: [] }
     }
   }
]);

一旦“布宜諾斯艾利斯”市不在“CA”省,則不返回任何內容。

注意傳遞給 Client.aggregate() 的數組接收的最后一個參數(作為對象):

{
  $match: {
    city: { $ne: [] }
  }
}

這告訴 MongoDB 為了返回數據 city 必須不等於空數組。

這樣問題就解決了。

暫無
暫無

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

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