我有两个 mongo 集合:
- 位置:(locationId、locationCity、locationState、locationZip 等)
- carLocations:{carId、carType、carMake、locationId}
我要检索数据
carAvailability: {locationCity, locationState, locationZip, carMake, carType}
在我的 nodejs 层中,这是我想要做的:
首先,我尝试通过 locationCity、locationState 或 locationZip 检索 locationId 数组。获得 locationId 数组后,我将尝试检索 carLocations。
app.get("/api/carsbylocationids", function (req, res) {
//console.log(" locationid:" + req.query.locationid);
var locationIds = JSON.parse(req.query.locationIds);
console.log("locationIds: " + locationIds);
console.log("carId: " + req.query.carId);
db.collection(carsLocations).find(
{
'locationId': {$in:locationIds},
'carId': req.query.carId
}
).toArray(function (err, docs) {
if (err) {
handleError(res, err.message, "Failed to get items.");
} else {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET);
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.status(200).json(docs);
}
});
});
在这部分或 angularJS 2 代码(此处未提供)中,我想要 carAvailability: {locationCity, locationState, locationZip, carMake, carType} 以便我可以遍历并显示在屏幕上。
我无法找到最佳/有效的方法。我应该在 nodeJS 层还是 Angular2 层处理这种连接类型的条件?
最佳答案
我使用 $lookup 和 $match 的聚合从 mongoDb 获取数据。对于那些想要细节的人:
app.get("/api/locationsByitemid", function (req, res) {
console.log(" itemid:" + req.query.itemid + " city:" + req.query.locationCity + " state:" + req.query.locationState);
db.collection(LOCATIONS_COLLECTION).aggregate([
{ $lookup: { from: ITEMS_COLLECTION, localField: "locationId",foreignField: "locationId", as: "locationsbyLocationId"} },
{ $unwind:"$locationsbyLocationId"},
{ "$match": { 'locationsbyLocationId.itemid': req.query.itemid, 'locationCity': req.query.locationCity, 'locationState' : req.query.locationState} }
]
).toArray(function (err, docs) {
if (err) {
handleError(res, err.message, "Failed to get items.");
} else {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.status(200).json(docs);
}
});
});
这是令我满意的工作,但欢迎提出任何建议....感谢那些指出最好在调用 RestFul 服务之前处理此问题的人。这就是我探索的内容。
关于javascript - MongoDb、NodeJs、Express 和 Angular 2,来自两个集合的数据连接、检索和显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44947794/