【问题标题】:Is there a way a to reuse mongodb/mongose aggregation code?有没有办法重用 mongodb/mongose 聚合代码?
【发布时间】:2020-05-15 16:57:26
【问题描述】:

我正在通过 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聚合代码可以复用吗?如果是这样,你怎么做?或者有没有其他方法可以避免重复代码?

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案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" } },
        ...
    ]);
    

    【讨论】:

    • 有没有办法将两个对象例如sortByLatestfindCreator 组合成一个对象?还是一个数组?我试图在我的代码中这样做,但它不起作用。
    • 我刚刚想通了。(我正在使用 javascript)。我将阶段分组为数组并使用spread operator 来“打开数组”。
    • @YulePale,我认为$sort$lookup 是不同的管道阶段,因此您可能无法将它们组合成一个操作。不过,您可以将它们一个接一个地放置在管道阵列中。您可以使用扩展运算符从先前的阶段数组创建一个新数组,甚至可以从前一个阶段创建一个新阶段,如上一个示例所示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多