Javascript MongoDb、NodeJs、Express和Angular 2、来自两个集合的数据连接、检索和显示
我有两个mongo系列:Javascript MongoDb、NodeJs、Express和Angular 2、来自两个集合的数据连接、检索和显示,javascript,node.js,mongodb,angular,express,Javascript,Node.js,Mongodb,Angular,Express,我有两个mongo系列: 位置:(locationId、locationCity、locationState、locationZip等) carlocation:{carId,carType,carMake,locationId} 我想检索数据 carAvailability: {locationCity, locationState, locationZip, carMake, carType} 在我的nodejs层中,以下是我试图做的: 首先,我尝试按locationCity、loca
- 位置:(locationId、locationCity、locationState、locationZip等)
- carlocation:{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服务调用之前处理的人。这就是我所探讨的。Http请求是前端最昂贵的操作之一。如果可以,请将它们合并到后端,这样您只能从fro发出一个Http请求nt end。当然这也取决于其他参数(可读性、复杂性等)。我同意@echonax,您可以在monogDB中使用填充功能进行此类连接。我们将探索mongoDB的“填充”功能。非常感谢您……不仅仅是“填充”,在发出http请求之前,我需要使用$lookup和aggregate功能来执行join。现在开始处理它…最好也是最简单的方法是使用populate。您可以查看一下它。此外,所有此类操作都可以在后端而不是前端完成。这将在许多方面具有时效性。