Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[IMPROVE] Use MongoBD aggregation to get users from a room #12566

Merged
merged 10 commits into from
Dec 4, 2018
35 changes: 25 additions & 10 deletions server/methods/getUsersOfRoom.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Meteor } from 'meteor/meteor';

Meteor.methods({
getUsersOfRoom(rid, showAll) {
async getUsersOfRoom(rid, showAll) {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getUsersOfRoom' });
Expand All @@ -16,17 +16,32 @@ Meteor.methods({
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getUsersOfRoom' });
}

const subscriptions = RocketChat.models.Subscriptions.findByRoomIdWhenUsernameExists(rid, { fields: { 'u._id': 1 } }).fetch();
const userIds = subscriptions.map((s) => s.u._id); // TODO: CACHE: expensive
const options = { fields: { username: 1, name: 1 } };

const users = showAll === true
? RocketChat.models.Users.findUsersWithUsernameByIds(userIds, options).fetch()
: RocketChat.models.Users.findUsersWithUsernameByIdsNotOffline(userIds, options).fetch();
const subscriptions = RocketChat.models.Subscriptions.findByRoomIdWhenUsernameExists(rid);

return {
total: userIds.length,
records: users,
total: subscriptions.count(),
records: await RocketChat.models.Subscriptions.model.rawCollection().aggregate([
{ $match: { rid } },
{
$lookup:
engelgabriel marked this conversation as resolved.
Show resolved Hide resolved
{
from: 'users',
localField: 'u._id',
foreignField: '_id',
as: 'u',
},
},
{
$project: {
'u._id': 1,
'u.name': 1,
'u.username': 1,
'u.status': 1,
},
},
...(showAll ? [] : [{ $match: { 'u.status': 'online' } }]),
{ $replaceRoot: { newRoot: { $arrayElemAt: ['$u', 0] } } },
]).toArray(),
};
},
});