Sunday, 7 May 2017

Get conversation's last message with unread count

I'm making an in app messaging system in which I have to show the list of conversations with their last message and the unread count. My schema is as follows--

var schema = new Schema({
    senderID: {
        type: Schema.Types.ObjectId,
        ref: 'Member'
    },
    receiversID: [{
        type: Schema.Types.ObjectId,
        ref: 'Member'
    }],
    content: {
        type: String,
        default: ''
    },
    isRead: {
        type: Boolean,
        default: false,
    },
    createdAt: {
        type: Number,
        default: Date.now
    }
});  

I did this initially to get all the conversations with their last message --

messageModel.aggregate(
            [{ $match: { senderID: userId } },
            { $unwind: '$receiversID' },
            { $sort: { createdAt: -1 } },
            { $group: { _id: '$receiversID', unreadCount: { $sum: { $cond: [{ $eq: ["$isRead", false] }, 1, 0] } }, senderID: { $first: '$senderID' }, receiversID: { $first: '$receiversID' }, content: { $first: '$content' } } },
            { $skip: pagingData.pageSize * (pagingData.pageIndex - 1) },
            { $limit: pagingData.pageSize }
            ], function (err, docs) {
                resolve(docs);
            }
        );

But it doesn't shows the messages if you are a receiver. I want to show the conversation whether you are receiver or sender.



via Mayank Baiswar

No comments:

Post a Comment