2014-04-25 109 views
2

我有兩個貓鼬模型。我們來調用一個模型foo和第二個模型欄。酒吧記錄有一個相關的foo記錄和一個電子郵件地址。我希望我的api能夠通過一個電子郵件地址並返回沒有使用該電子郵件地址創建的酒吧記錄的foo記錄列表。我怎麼會用貓鼬做這個?貓鼬/ mongodb查詢沒有相關記錄的記錄

我知道我可以用SQL編寫這個查詢,但是我一直在試圖學習一個沒有sql db,因此mongo。

這裏是一個例子。我有2個富記錄和2個記錄:

FOOS:

{name:"first foo"} 
{name:"second foo"} 

和我的酒吧記錄:

{ 
    email:"[email protected], 
    foo_id:first_foo._id 
} 

{ 
    email:"[email protected], 
    foo_id:second_foo._id 
} 

我的API請求會來的電子郵件:requestEmail @例子。 COM。在這種情況下,我想返回第二個foo(和任何其他foo記錄),因爲第一個foo在請求中包含帶有電子郵件的條形記錄。

+1

您可以將生成的文檔或記錄粘貼到mongo中。您的文檔在MongoDB中的樣子 –

+0

Aleksandar的現有答案看起來很正確。是什麼促使你添加賞金?如果他的答案有些特定的問題無效,那麼如果您添加了關於該問題的評論,這將會很有幫助。 – JohnnyHK

+0

@ pka2012由於這裏沒有太多細節,我正在做一些假設。在我的選擇中,您應該更改模式,以便鏈接兩個模型。 – Foreever

回答

3

它可能是最容易做到這一點的兩次。首先,你應該檢索所有的Bar對象,然後根據它們過濾你的Foo對象。我沒有node.js編譯器,所以我的代碼中包含一些錯誤(我可以在白天晚些時候編輯它,但你會得到圖片)。

var findFooWOutBar = function(theEmail) 
{ 
    Bar.find({email: theEmail}, function(err,docs) 
    { 
    if(err) 
    { 
     console.log(err); 
     return 
    } 
    else 
    { 
     var barIds=[]; 
     docs.forEach(function(bar) //fetching all of the bars with the email 
     { 
     barIds.push(bar._id);//or whatever you are using as a reference 
     }); 

     //nin means not in 
     Foo.find().nin('barRef', barIds).exec(function(err,foos) 
     { 
     //process your Foo results (foos) here 
     }); //have not tested this, but according to the docs it should go something like this  
    } 
    }); 

} 

所以基本上,或許真的是不完全正確的在這裏,但你需要吧ID(或正在使用其他的參考鍵)的陣列,並將其與使用尼恩(不)的結合。

0

我認爲你應該先改變你的模式。 杆模式可以被定義如下:

var Schema = require('mongoose').Schema; 
var barSchema = new Schema({ 
    email: { 
     type: String, 
     unique: true 
    }, 
    fooId: { 
    type: Schema.Types.ObjectId 
    }, 
}); 

現在,fooSchema可以被定義如下:

var Schema = require('mongoose').Schema; 
var fooSchema = new Schema({ 
    name: { 
     type : String 
    } 
}); 

好吧,我們已經得到了我們的架構。現在我們可以定義模型併爲解決方案工作。

var model = require('mongoose').model; 
var foo = model('Foo', fooSchema); 
var bar = model('Bar', barSchema); 

function fooWithNoBar(email) { 
    var conditions = { 
     email: email 
    } 
    bar.find(conditions, function (err, data) { 
     if (err) { 
      console.log(err); 
      return 
     } else { 
      var barIds = []; 
      data.forEach(function (bar) { 
       barIds.push(bar._id); 
      }); 
      conditions = { 
        _id: { 
         $nin: barIds 
        } 
       } 
      foo.find(conditions, function (err, data) { 
       console.log("foo records that do not have a bar record created with that email address: ", data); 
      }); 
     } 
    }); 
} 

注:我已經複製從亞歷山大的回答一些代碼。