MongoDb,NodeJs,Express和Angular 2,来自两个集合的数据join,复制和显示

我有两个mongo集合:

  • 位置:(locationId,locationCity,locationState,locationZip等)
  • carLocations:{carId,carType,carMake,locationId}

我想检索数据

carAvailability: {locationCity, locationState, locationZip, carMake, carType} 

在我的nodejs层,这是我想要做的:

首先,我试图通过locationCity,locationState或locationZip检索locationIds数组。 一旦我有了一系列的locationIds,我正试图找回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层处理这种连接types的条件?

我使用了$ 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); } }); }); 

这是令我满意的工作,但任何build议,欢迎….感谢那些指出,这是RestFul服务电话之前最好的处理。 那是我探索的。