Nodejs mongoose复杂的查询

我无法理解这一点。 我试图得到一个查询结果在mongoose。 我有一个旅行数据库,其中包括一个停止的路线。 我想要得到所有访问目标站的旅程(奖金:并使用某个平台)。

这是模式的样子:

var StopSchema = new Schema({ arrival: String, departure: String, platform: String, station: String, }); var JourneySchema = new Schema({ trainNumber: String, destination: String, route: [StopSchema] }); 

exampleData:

 { trainNumber: '1', destination: 'Z', route: [ { arrival: "11:23", departure: "11:25", platform: "3", station: "A"}, { arrival: "11:33", departure: "11:35", platform: "3", station: "B"}, { arrival: "11:43", departure: "11:45", platform: "3", station: "Z"} ] }, { trainNumber: '2', destination: 'Z', route: [ { arrival: "12:23", departure: "12:25", platform: "3", station: "A"}, { arrival: "12:33", departure: "12:35", platform: "3", station: "B"}, { arrival: "12:43", departure: "12:45", platform: "3", station: "Z"} ] }, { trainNumber: '3', destination: 'F', route: [ { arrival: "12:23", departure: "12:25", platform: "3", station: "D"}, { arrival: "12:33", departure: "12:35", platform: "3", station: "E"}, { arrival: "12:43", departure: "12:45", platform: "3", station: "Z"} ] } 

请求:获取访问“B”的所有旅程(在平台3上),列出路线并提升目标站数据

desiredResult:

 [ { trainNumber: '1', destination: 'Z', route: [ { arrival: "11:23", departure: "11:25", platform: "3", station: "A"}, { arrival: "11:33", departure: "11:35", platform: "3", station: "B"}, { arrival: "11:43", departure: "11:45", platform: "3", station: "Z"} ], targetStation: { arrival: "11:33", departure: "11:35", platform: "3", station: "B"} }, { trainNumber: '2', destination: 'Z', route: [ { arrival: "12:23", departure: "12:25", platform: "3", station: "A"}, { arrival: "12:33", departure: "12:35", platform: "3", station: "B"}, { arrival: "12:43", departure: "12:45", platform: "3", station: "Z"} ], targetStation: { arrival: "12:33", departure: "12:35", platform: "3", station: "B"} } ] 

我只是不知道我可以使用elemmatch / aggregate / virtual / query的什么邪恶组合。

由于MongoDB不支持连接,因此无法在具有所需模式的单个查询中执行此操作。 您至less需要两个查询:一个获取目标停靠点的ID,然后一个获取已停止的行程。 像(假设模型StopJourney ):

 Stop.findOne({station: 'B', platform: '3'}).exec().then(function(stop) { if (stop === null) { throw new Error('No stop matches request'); return Journey.find({route: {_id: stop.id}}).populate('route').exec(); }).then(function(journeys) { if (journeys === null || journeys.length === 0) { throw new Error('No journeys include requested stop'); } // `journeys` should be an array matching your desired output // you can add the extra property here or in the journeys query if you wish }).then(null, function (err) { // Handle errors });