我无法理解这一点。我试图在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的邪恶组合。
答案 0 :(得分:1)
由于MongoDB不支持联接,因此无法在具有所需架构的单个查询中执行此操作。您将需要至少两个查询:一个用于获取目标停靠点的ID,然后是第二个用于获取具有该停靠点的行程。类似的东西(假设模型Stop
和Journey
):
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
});