【发布时间】:2023-03-23 06:11:01
【问题描述】:
我目前正在使用猫鼬进行具有以下架构的项目。
用户架构
const userSchema = {
name: string
email: string
medicalVisits: [{type: Schema.ObjectId, ref: "records"}]
createdAt: Date
}
记录架构
const recordSchema = {
medication: [String],
rating: Number
user: [{type: Schema.ObjectId, ref: "user"}]
tests: [{type: Schema.ObjectId, ref: "tests"}]
createdAt: Date
}
测试架构
testScore: Number
answers: Object
user: [{type: Schema.ObjectId, ref: "user"}]
createdAt: Date
从上面的小架构中,我有一个设置,患者可以多次进行测试,并且他们各自的测试保存在 Tests collection 中。此外,date 会记录他们参加的所有测试。医生可以请求查看患者的记录,在这种情况下,患者只有一个 record document,其中嵌入了他们的 tests records。目前,我面临的问题是获取患者最新和最旧的测试分数以及他们的初始详细信息。
我可以做一个猫鼬填充来获取有关用户的所有信息,例如
await User.findById(userId).populate({
path: "medicalVisits"
model: "records"
populate: {
path: "tests"
model: "test"
}
})
该操作会返回患者的记录以及他们自注册以来所做的所有测试。但是当我对数据库进行这样的调用时,我只想检索患者的最新和最旧的分数。换句话说,我想获得患者Initial test score,以及他们最近的测试成绩。我是Mongoose aggregation 的新手,我尝试使用Mongoose aggregate 函数,但它返回一个空数组,我想我错过了一些东西。
目前,这是我的聚合管道的样子。
const user = await Doctor.aggregate([
{ $match: { _id: docId } },
{
$lookup: {
from: "users",
localField: "patients",
foreignField: "_id",
as: "patients",
},
},
{ $unwind: "$patients" },
{ $unwind: "$patients.medicalVisits" },
{
$lookup: {
from: "records",
localField: "patients.user",
foreignField: "_id",
as: "patientRecord",
},
},
{ $unwind: "$patientRecord" },
// { $sort: { createdAt: 1 } },
{
$group: {
_id: docId,
user: { $last: "$patients" },
record: { $last: "$patientRecord"}
},
},
]);
return user[0];
从上面的sn-p,我的意图是:
给定doctor Id,他们可以看到他们的患者列表,还可以看到他们最新和最旧的测试成绩。
预期输出
const output = {
userId: 6e12euido....
name: "John doe"
email: "john@john.com"
rating: 2
initialTestScore: 10
recentTestScore: 30
}
我该怎么做?或者有什么更好的选择?非常感谢。
【问题讨论】:
-
在你的第二个
$lookup阶段,应该是localField: "patients.medicalVisits"
标签: node.js mongodb mongoose aggregation-framework