【发布时间】:2020-09-15 17:20:03
【问题描述】:
我有一些看起来像这样的模型:
const exerciseDetailSchema = new mongoose.Schema(
{
Translations: {
Name: {
en: { type: String, required: true },
no: { type: String }
}
}
}
);
const workoutDetailSchema = new mongoose.Schema(
{
Sets: {
Exercises: [ WorkoutExercises ],
Units: { type: String }
}
}
);
const WorkoutSets = new mongoose.Schema({
Reps: { type: Number },
Weight: { type: Number }
});
const WorkoutExercises = new mongoose.Schema({
ExerciseId: { type: String, required: true },
Sets: [ WorkoutSets ]
});
基本上,锻炼由集合组成,其中包含一些元数据,包括锻炼。这些练习是一个由锻炼集组成的数组。
我正在尝试进行查询,该查询将返回给我的锻炼详细信息,包括锻炼名称,使其看起来像这样:
{
_id: "5f60dc1069c27c015ede4e3e",
Sets: {
Units: 'metric',
Exercises: [
{
_id: "5f60dc1069c27c015ede4e3e",
ExerciseId: "5f60c3b7f93d8e00a1cdf414",
ExerciseName: {
en: "Squat",
no: "Knebøy"
},
Sets: [
{ _id: "5f60dc1069c27c015ede4e3f", Reps: 10 },
{ _id: "5f60dc1069c27c015ede4e40", Reps: 20 }
]
}
]
}
}
这将是一个示例练习,例如:
{
_id: "5f60c3b7f93d8e00a1cdf414",
Translations: {
Name: {
en: "Squat",
no: "Knebøy"
}
}
}
我尝试过使用 $lookup,如下所示:
const workout = await WorkoutDetail.aggregate([
{
$lookup: {
from: ExerciseDetail.collection.name,
localField: "Sets.Exercises.ExerciseId",
foreignField: "_id",
as: "ExerciseDetail"
}
}
]);
但它总是只返回:ExerciseDetail: [] 用于应该“加入”的部分。谁能提供有关如何正确查询此问题的任何帮助?
更新
我在这里的另一个问题中询问了有关对这些数据进行分组的问题,并收到了一个完美的答案。希望它也可以对其他人有所帮助: MongoDB $group (mongo playground)
【问题讨论】: