在 Mongoose 中使用连接和过滤器进行查询
Posted
技术标签:
【中文标题】在 Mongoose 中使用连接和过滤器进行查询【英文标题】:Querying with joins & filters in Mongoose 【发布时间】:2017-02-19 15:36:39 【问题描述】:我是 Mongodb 的新手,我在使用 MEAN 堆栈构建的 Web 应用程序中使用它。我的目标是通过加入两个表并对它们应用过滤条件来查询它们。例如:我有两张表 - Bike-BikeID,Registration No.,Make,Model & Appointment - Appointment Date,Status,Bike(ref Bike object) 我只想显示那些没有预约状态的自行车= '预订'。我想在 Mongoose 中完成以下 SQL。
Select bike.* from Bike inner join Appointment on Bike.BikeID = Appointment.BikeID and Appointment.Status != 'Booked'
我正在使用以下代码,但没有得到想要的结果。有人可以帮我解决这个问题。
app.get('/api/getbikeappo*',function(req,res)
var msg="";
//.find(cust:req.query._id)
//.populate('cust','email')
ubBike.aggregate([
$match:
cust : req.query._id
,
$lookup:
from: "appos",
localField: "_id",
foreignField: "bike",
as : "appointments"
,
$match:
"appointments" : $eq : []
])
.exec(function(err,bikes)
res.send(bikes);
if(err) throw err;
);
);
bikes - collection
"_id":
"$oid": "57fb600fdd9070681de19c18"
,
"brand": "Splendor",
"model": "Splendor",
"year": "2002",
"kms": 0,
"regno": "TN02M8937",
"cust":
"$oid": "57f8c44466cab97c1355a09a"
,
"__v": 0
"_id":
"$oid": "57fb6025dd9070681de19c19"
,
"brand": "Activa",
"model": "Activa",
"year": "2016",
"kms": 0,
"regno": "TN14M3844",
"cust":
"$oid": "57f8c44466cab97c1355a09a"
,
"__v": 0
appointment collection
----------------------
"_id":
"$oid": "57fb6040dd9070681de19c1a"
,
"appoidt":
"$date": "2016-10-15T18:30:00.000Z"
,
"reqdt":
"$date": "2016-10-10T09:32:48.694Z"
,
"status": "Booked",
"bike":
"$oid": "57fb600fdd9070681de19c18"
,
"cust":
"$oid": "57f8c44466cab97c1355a09a"
,
"__v": 0
-----------------
Expected output is
"_id":
"$oid": "57fb6025dd9070681de19c19"
,
"brand": "Activa",
"model": "Activa",
"year": "2016",
"kms": 0,
"regno": "TN14M3844",
"cust":
"$oid": "57f8c44466cab97c1355a09a"
,
"__v": 0
【问题讨论】:
发布您的文档样本以及您期望的输出? @ClementAmarnath 完成 【参考方案1】:你快到了,你只需要正确的 $match
查询如下:
ubBike.aggregate([
"$match": "cust": req.query._id ,
"$lookup":
"from": "appos",
"localField": "_id",
"foreignField": "bike",
"as": "appointments"
,
"$match": "appointments.status": "$ne": "Booked"
]).exec(function(err, bikes)
if(err) throw err;
res.send(bikes);
);
【讨论】:
以上是关于在 Mongoose 中使用连接和过滤器进行查询的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Node.js 中通过 Mongoose 使用 dot(.) 进行查询以及如何添加空数组