2017-04-13 16 views
0

現在MeteorにWebアプリケーションを作成しています。このアプリはMongoDbを使用しており、クライアントからクエリを作成する際には、minimongoを使用して基礎となるmongoDbとやり取りします。minimongoを使って複数のmongoコレクションからデータを取得する方が良い

私は

const chats = { 
     userIds: [], 
     //other data irrelevant to question 
    }; 

const users = { 
      userId: string, 
      username: string 
      //other data irrelevant to question 
     }; 

の下に定義された2つのコレクションを持っているので、基本的に、チャットコレクションは、チャット内のすべてのユーザーに対して一意のユーザーIDを格納し、ユーザーのコレクションには、システム内のすべてのユーザーが含まれています。私は、1つのチャット・ドキュメント内のユーザーのすべてのユーザー名を照会しようとしています。現在

私はそのようにように、それに対応するユーザ名を見つけるために、これらのユーザーIDの上で繰り返し処理するJavaScriptを使用して、単一のチャットですべてのユーザーIDのために最初のクエリでこれを実現しています:

var thisChat = Chats.findOne(this.chatId); //get current chat document 
      var userList = thisChat.userIds; //get list of user id's from this chat  

      this.newUserList = []; 
      for(var i = 0; i < userList.length; i++) { //iterate over user id's 
       var tempUser = Meteor.users.find({_id: userList[i]}).fetch(); //find username for this userId 
       this.newUserList.push(tempUser[0]); //add this username to an array 
      } 
      }); 
     }); 

    return this.newUserList; //return list of usernames 

この方法はかなりあります醜いので、私は、これを行うためのクリーナーな方法があるかどうか疑問に思っています。私は、人口集計や集計を行った他の投稿を見てきましたが、これはminimongoでは利用できません。

答えて

1

サーバーレベルでserverTransform packageを使用してこれを行う方法は次のとおりです。

Meteor.publishTransformed('currentChat', function() { 
     return Chats.find() 
     .serverTransform({ 
      'usernames': function(chat) { 
       return Meteor.users.find({ 
       _id: { 
        $in: chat.userIds 
       } 
       }).map(function(user) { 
        return user.username; 
       } 
       } 
      }); 
     }); 

今、あなただけのオブジェクト自体からそれを得ることができます。

var thisChat = Chats.findOne(this.chatId); 
var usernames = thisChat.usernames; 

もう一つの人気パッケージには、クライアント上のユーザーとチャットを持っているなら、あなたはすべてのループとプッシュ避けるために.map()続くあなたの検索で$in:演算子を使用することができますpublish-composite

0

です。

const usernames = Meteor.users.find(
    { _id: { $in: Chats.findOne(this.chatId).userIds }} 
).map(doc => doc.username); 
関連する問題