我通过 mongoose 使用 mongodb。我有许多看起来几乎相似的 mongodb 聚合查询,因此聚合代码有 90% 相似。我可以重用 mongodb 聚合代码以避免重复吗?或者我如何将 mu 代码库设计为 DRY?
例如,考虑下面的代码:
CreatedPost.aggregate([
// $match can be dynamic
{$sort: { createdAt: -1 } },
{$lookup:{from:"users",localField:"creator",foreignField:"_id",as:"userWhoCreatedThisPost"}},
// Plus other lookups like likes comments etc
{$project:{
userWhoCreatedThisPost:{
_id:'$userWhoCreatedThisPost._id',
name:'$userWhoCreatedThisPost.name',
},
postText:'$postText',
createdAt : '$createdAt',
numberOfLikes:{$size:'$likes'},
numberOfComments:{$size:'$comments'},
// plus many more details
}}
])
在上面的查询中,您只需更改(或添加)$match
参数即可将代码用于不同目的。例如,如果您想要将帖子显示到时间线,或者您想要仅该用户创建的帖子,或者您只想要一篇帖子。
是否可以重用mongodb聚合代码?如果是这样,你会怎么做?或者有其他方法可以避免重复代码吗?
最佳答案
当然,这是一个简单的对象,因此您可以将该对象保留在某处并重用它,或者创建一个可以根据您想要的任何内容进行参数化的函数,这将返回该对象。
您甚至可以保留它的一部分并重新组装:
let sortByLatest = { $sort: { createdAt: -1 } };
let findCreator = { $lookup: { from: "users", localField: "creator", foreignField: "_id", as: "userWhoCreatedThisPost" } };
// ...
CreatedPost.aggregate([ sortByLatest, findCreator, ... ]);
或者有返回部分的函数:
let matchStatus = (status) => ({ $match: { status } });
CreatedPost.aggregate([ sortByLatest, findCreator, matchStatus("Done"), ... ]);
或者在应用时修改部件:
CreatedPost.aggregate([
// pick a different collection, but keep the rest of the lookup
{ $lookup: { ...findCreator["$lookup"], from: "authors" } },
...
]);
关于mongodb - 有没有办法重用 mongodb/mongose 聚合代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61815184/