gpt4 book ai didi

javascript - Nodejs Mongoose 复杂查询

转载 作者:可可西里 更新时间:2023-11-01 10:43:11 24 4
gpt4 key购买 nike

我只是无法理解这个问题。我试图在 Mongoose 中获得查询结果。我有一个旅程数据库,其中包括停靠路线。我想获得访问目标站的所有旅程(奖励:并使用某个平台)。

这是模式的样子:

var StopSchema = new Schema({
arrival: String,
departure: String,
platform: String,
station: String,
});

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

示例数据:

{
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)的所有旅程,列出路线并推广目标站数据

期望结果:

[
{
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 不支持联接,因此您无法在使用所需架构的单个查询中执行此操作。您将至少需要两个查询:一个用于获取目标站点的 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
});

关于javascript - Nodejs Mongoose 复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29615695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com