试图在猫鼬中设计类似Facebook的通知。需要帮助汇总

时间:2016-08-21 02:16:35

标签: mongodb mongoose

与Facebook一样,我想汇总结果。但我无法弄清楚如何去做。

示例:

让我们说10个用户喜欢我的帖子。 我不想收到10条通知。 1当然足够了。

这是我的架构:

var eventLogSchema = mongoose.Schema({
    //i.e. Somebody commented, sombody liked, etc.
    event: String, 

    //to a comment, to a post, to a profile, etc.
    toWhat: String, 

    //who is the user we need to notify?
    toWho: {type: mongoose.Schema.Types.ObjectId, ref:'User'}, 

    //post id, comment id, whatever.. 
    refID: {type: mongoose.Schema.Types.ObjectId},         

    //who initiated the event.
    whoDid: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, 

    // when the event happened
    date: {type:Date, default: Date.now()},

    //whether the user already saw this notification or not.
    seen: {type:Boolean, default: false}     
    })

所以我需要计算时间

Ex.1: event='liked' and toWhat="post" and refID=myPostID and seen=false

但与此同时,我想在'谁'路径,所以我可以显示"迈克尔和其他9个人喜欢你的帖子(链接到帖子)"

我能想到的每一种方式都很笨拙,并且需要多次查询,感觉它们会花费大量的系统资源,我想知道是否有一种简单的方法可以做到这一点。

实际上它变得更加复杂。

我不想像在Ex.1中那样指定值。 相反,我想说

aggregate all events with similar 'event', 'toWhat', 
'refID' with value seen=false and populate the last one on the 'who' path.

会喜欢一些阅读材料,链接,建议或任何东西。

谢谢!

1 个答案:

答案 0 :(得分:0)

管理这样解决它。

不确定它是否最佳,但它确实有效。

//The name of my Schema
Notification.aggregate([
        {
            $match: {
                //I only want to display new notifications
                seen: {$ne: true}
                //to query a specific user add
                // toWho: UserID
            }
        },
        {
            $group: {
                //groups when event, toWhat, and refID are similar
                _id: {
                    event: '$event',
                    toWhat: '$toWhat',
                    refID: '$refID',

                },
                //gets the total number of this type of notification
                howMany: {$sum: 1},
                //gets the date of the last document in this query
                date: {$max: '$date'},
                //pulls the user ID of the last user in this query
                user: {$last: '$whoDid'}
            }
        }

    ]).exec(function (err, results) {
        if (err) throw err;
        if (results) {
            //after I get the results, I want to populate my user to get his name.
            Notification.populate(results, {path: 'user', model: "User"}, function (err, notifications) {
                if (err) throw err;
                if (notifications) res.send(notifications);
            })
        }

    })

我不确定是否可以在一个查询中填充汇总结果,我认为如果它可能是最佳的,但到目前为止,这对我来说似乎是可以接受的需要。

希望这会有所帮助。