У меня есть массив students
в моих Документах VirtualClass
, и моя цель - создать список без дублирования учеников.
Я хочу сопоставить VirtualClass
с учителем, а затем $push
ученик в массив.
Схема виртуального класса
const VirtualClassSchema = new Schema({
name: { type: String, required: true },
descriptionHeading: { type: String, required: true },
room: { type: String },
teacher: {
userId: { type: Schema.Types.ObjectId, ref: "User" },
name: { type: String },
profile_picture: { type: String }
},
students: [
{
userId: { type: Schema.Types.ObjectId, ref: "User" },
name: { type: String },
profile_picture: { type: String }
}
],
...
Мой текущий запрос выглядит следующим образом
VirtualClass.aggregate([
{ $match: { "teacher.userId": user._id } },
{
$group: {
_id: null,
students: { $addToSet: "$students" }
}
}
])
, который возвращает:
[
{
"_id": null,
"students": [
[
{
"_id": "5e84d1a1ab3ebf54283b8cb2",
"userId": "5dd27452592f600900235945",
"name": "student zero",
"profile_picture": "https://productionstemulistorage.blob.core.windows.net/stemuli/profile-picture-6e609f3b-44cb-44c0-888a-1b6767e3072d"
}
],
[
{
"_id": "5e84d1a1ab3ebf54283b8cb4",
"userId": "5dd27452592f600900235945",
"name": "student zero",
"profile_picture": "https://productionstemulistorage.blob.core.windows.net/stemuli/profile-picture-6e609f3b-44cb-44c0-888a-1b6767e3072d"
}
]
]
}
]
Ожидаемые результаты:
_id: null,
"students":
[
{
"_id": "5e84d1a1ab3ebf54283b8cb4",
"userId": "5dd27452592f600900235945",
"name": "student zero",
"profile_picture": "https://productionstemulistorage.blob.core.windows.net/stemuli/profile-picture-6e609f3b-44cb-44c0-888a-1b6767e3072d"
}
]
Спасибо!