2014-04-25 106 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); 
      }); 
     } 
    }); 
} 

注:我已经复制从亚历山大的回答一些代码。