例如,我有50个用户,我有像
这样的集合Rooms = new Mongo.Collection('rooms');
首先,我想混合用户,如果我有[id1,id2,id3...]
这样做[id52,id91241,id2...]
并且在每个Room
5个用户之后输入
for (i=0;i<countofmyusers;i=i+5)
crete new room and put 5 users // ?? how .. Rooms.insert(??)
{
users: [id1,id44,id2451,id921241,id23]
...
}
知道该怎么做吗?
答案 0 :(得分:1)
这是一个创建一组房间的示例函数,每个房间都有一个随机的用户样本:
var randomRooms = function(roomCount, sampleSize) {
// extract all of the user ids in the datbase
var userIds = _.pluck(Meteor.users.find({}, {fields: {_id: 1}}).fetch(), '_id');
// create roomCount rooms
_.times(roomCount, function() {
// insert a new room with a random sample of users of size sampleSize
Rooms.insert({users: _.sample(userIds, sampleSize)});
});
};
这是一个新版本,强制用户ID不会在群组之间重复(即每个用户将被分配到一个且只有一个群组):
var randomRooms = function(userCountInEachRoom) {
// extract all of the user ids in the datbase
var userIds = _.pluck(Meteor.users.find({}, {fields: {_id: 1}}).fetch(), '_id');
// create a new array of randomly sorted user ids
var shuffledUserIds = _.shuffle(userIds);
// create a list of lists of user ids where each list has at most
// userCountInEachRoom ids - note that users will not be repeated in any lists
var userLists = [];
while (shuffledUserIds.length > 0)
userLists.push(shuffledUserIds.splice(0, userCountInEachRoom));
// insert a new group for each sub-array of user ids
_.each(userLists, function(users) {
Rooms.insert({users: users});
});
};
您可以将其称为randomRooms(5)
,以便在每个组中放置最多五个用户。请注意,如果总用户数不是五的倍数,则最后一个组的用户数将少于五个。