mongoose/ mongodb查询没有相关logging的logging

我有两个mongoose模型。 我们来调用一个模型foo和第二个模型吧。 酒吧logging有一个相关的foologging和一个电子邮件地址。 我希望我的api能够通过一个电子邮件地址,并返回没有使用该电子邮件地址创build的酒吧logging的foologging列表。 我怎么会用mongoose做这个?

我知道我可以用SQL编写这个查询,但是我一直在试图学习一个没有SQL的数据库,因此mongo。

这是一个例子。 我有2条logging和2条logging:

FOOS:

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

和我的酒吧logging:

 { email:"requestEmail@example.com, foo_id:first_foo._id } { email:"someOther@example.com, foo_id:second_foo._id } 

请求我的api将通过电子邮件发送到:requestEmail@example.com。 在这种情况下,我想要返回第二个foo(和任何其他foologging),因为第一个foo在请求中包含带有电子邮件的条形logging。

它可能是最简单的做两次。 首先,你应该检索所有的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 } }); } 

所以基本上,也许这里不完全正确,但是你需要一个Bar id(或者你正在使用的其他引用键)的数组,并且把它和使用nin(不在)结合起来。

我想你应该先改变你的模式。 bar模式可以定义如下:

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

好的,我们有了我们的模式。 现在我们可以定义模型,并通过解决scheme。

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

注意:我已经从Aleksandar的答案中复制了一些代码。