【发布时间】:2023-03-26 05:55:01
【问题描述】:
我想在聚合后填充引用模型。 到目前为止,我有这个解决方案。我想填充用户对象。它有姓名、电子邮件、电话字段。聚合运行良好,我得到了想要的结果,但用户字段没有得到填充。我已经阅读了很多类似的解决方案,但不幸的是,它们都没有奏效。
exports.getResultToCompetition = asyncHandler(async (req, res, next) => {
let competitionId = await Competition.findById(req.params.competitionId).select("_id");
const result = await Result.aggregate([
{
// $match: { competition: mongoose.Types.ObjectId("competitionId") },
$match: { competition: mongoose.Types.ObjectId(competitionId._id) },
},
{
$project: {
points: 1,
kilogramms: 1,
sector: 1,
user: 1,
competition: 1,
place: 1,
},
},
{
$group: {
_id: "$sector",
res: { $push: "$$ROOT" },
},
},
{
$sort: {
kilogramms: -1,
},
},
]);
await Result.populate(result, { path: "user", select: "email name avatar flag" });
res.status(200).json({ success: true, data: result });
});
我也尝试过,但没有用。
await Result.populate(result, {
path: "result",
populate: {
path: "res",
model: "Result",
populate: {
path: "user",
model: "User",
select: "email name avatar flag",
},
},
});
这就是我在 Postman 中得到的。
{
"success": true,
"data": [
{
"_id": "A",
"res": [
{
"_id": "5eaeab6b2b9f246693a65659",
"points": 14,
"kilogramms": 14,
"place": 14,
"sector": "A",
"competition": "5eaeaa5448580765da33165a",
{
"_id": "5eaec018784ea96aa7daeebe",
"points": 23,
"kilogramms": 23,
"place": 12,
"sector": "A",
"competition": "5eaeaa5448580765da33165a",
//Expected output includes the user object
"user": {
"_id": "5eaebf3471aab66a84ae01a4",
"name": "John Mayer",
"email": "johnmayer@gmail.com",
"phone": "123456789"
}
},
},
{
"_id": "5eaec018784ea96aa7daeebe",
"points": 23,
"kilogramms": 23,
"place": 12,
"sector": "A",
"competition": "5eaeaa5448580765da33165a",
"user": "5eaebf3471aab66a84ae01a4"
},
{
"_id": "5eaec028784ea96aa7daeebf",
"points": 12,
"kilogramms": 12,
"place": 14,
"sector": "A",
"competition": "5eaeaa5448580765da33165a",
"user": "5eaebf7f784ea96aa7daeeba"
}
]
},
{
"_id": "B",
"res": [
{
"_id": "5eaec03c784ea96aa7daeec0",
"points": 30,
"kilogramms": 34,
"place": 1,
"sector": "B",
"competition": "5eaeaa5448580765da33165a",
"user": "5eaebfa7784ea96aa7daeebb"
},
{
"_id": "5eaec04c784ea96aa7daeec1",
"points": 21,
"kilogramms": 20,
"place": 2,
"sector": "B",
"competition": "5eaeaa5448580765da33165a",
"user": "5eaebfd4784ea96aa7daeebc"
},
{
"_id": "5eaec05a784ea96aa7daeec2",
"points": 13,
"kilogramms": 13,
"place": 3,
"sector": "B",
"competition": "5eaeaa5448580765da33165a",
"user": "5eaebff5784ea96aa7daeebd"
}
]
}
]
}
【问题讨论】:
-
你能给出示例文件和预期的输出吗?
-
请添加到问题中。结果和用户集合文档,以及预期的输出。你在邮递员中得到的也不是必需的。
-
我已将预期输出添加到第一个对象
-
好的,你能看看我的回答吗?我还清除了一些不必要的行。
-
是的,谢谢 :) 我已经删除了第一行。这是不必要的。 :)
标签: node.js mongodb express mongoose aggregation-framework