Open uniquejava opened 8 years ago
Room.find({'members.userid': me}, function (err, rooms) {
var funcs = [];
_.each(rooms, function (room) {
var roomId = room.room;
console.log('====== each ' + roomId);
var meObj = _.findWhere(room.members, {userid: me});
var lastRead = meObj.last_read;
room = _.pick(room, 'room', 'name');
funcs.push(_.partial(calcUnread, room, lastRead));
});
async.parallel(funcs, function (err, results) {
res.json({groups: results, msgs: msgs});
});
});
function calcUnread(room, lastRead, cb) {
var unread_cnt = 0;
var q = Message.aggregate([
{$match: {room: room.room, crt_time: {$gt: lastRead}}},
{
$group: {
_id: null,
count: {$sum: 1}
}
}
]);
q.exec(function (err, result) {
if (err) {
console.error(err);
}
if (result.length > 0) {
unread_cnt = result[0].count;
}
console.log('unread_cnt is ' + unread_cnt);
room['unread_cnt'] = unread_cnt;
cb(null, room);
});
}
https://github.com/alsotang/async_demo