有没有一种方法可以重用mongodb / mongose聚合代码?

时间:2020-05-15 08:42:26

标签: mongodb mongoose mongodb-query aggregation-framework

我通过猫鼬使用mongodb。我有许多看起来很相似的mongodb聚合查询,因此聚合代码类似90%。我可以重用mongodb aggregaion代码来避免重复吗?或如何将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聚合代码?如果是这样,您该怎么做?还是有避免重复代码的另一种方法?

1 个答案:

答案 0 :(得分:1)

当然,这是一个简单的对象,因此您可以将对象保留在某个地方并重用它,或者创建一个可以根据需要设置参数的函数,该函数将返回该对象。

您甚至可以保留其中的一部分并重新组装:

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" } },
    ...
]);