2016-03-28 14 views
0

我希望查找所有用戶,而不是當前用戶。一對用戶都是此收集結構下存儲在「房間」陣列內:從用戶數組中篩選用戶ID

結構中的每個房間(從另一個HTML頁)的

var newRoom = Rooms.insert({ 
    owner : Meteor.userId(), 
    receiver : receiver, 
    people : [ owner , receiver ], 
}); 

Collection.js(使用dburles收集幫助)

Rooms.helpers({ 
    receiverName: function() { 
    return Meteor.users.findOne({ _id: this.receiver }).username; 
    } 
}); 

HTML

<!-- **allRooms.html** Works fine, names appear --> 
    {{#each rooms}} {{receiverName}}{{/each }} 

<!-- **roomDetail.html** names dont show, this.receiver undefined --> 
    {{receiverName}} 

roomDetail JS模板幫手

self.subscribe('room', Router.current().params._id); 
self.subscribe('users'); 
}); 

怎樣退還,並顯示用戶的ID,那不是從people領域這是一個數組當前用戶?我希望將其顯示在子頁面(roomDetail)中。

回答

1

假設:

  • Rooms是一個集合,並且你已經有了一個room文檔搜索上。
  • 您只想獲取單個用戶。

這給一試:

// The list of userIds in room minus the current user's id. 
var userIds = _.without(room.People, Meteor.userId()); 

// Assuming we want only one user... 
var user = Meteor.users.findOne({ _id: userIds[0] }); 

你的原碼的幾點思考:

  • 不能在您Meteor.users選擇到Rooms引用,除非Rooms是用戶的一個領域。 Mongo沒有加入的概念。
  • $ne是不是你想要的。如果您發佈了100個用戶,並且您的陣列僅包含2個用戶(其中​​一個用戶不想),則使用$ne將返回99個用戶。

根據您的意見,它看起來像你需要這一場collection helper。也許是這樣的:

Rooms.helpers({ 
    findUser: function() { 
    var userIds = _.without(this.People, Meteor.userId()); 
    return Meteor.users.findOne({ _id: userIds[0] }); 
    }, 
}); 
在你的代碼

然後在其他地方,對於一個給定room例如,你可以這樣做:

room.findUser() 
+0

我不知道如何回答這個問題。也許你會從客戶端的某個助手處返回'user'? –

+0

我用示例集合助手更新了答案。也許這將有助於引導你朝着正確的方向前進。 –

+0

我更新了與ES5兼容的答案。是的,這個幫手以一個房間作爲上下文,所以也許是'{{#with room}} {{#with findUser}} ... {{/ with}} {{/ with}}'或者什麼。再一次,我很難確切地說要寫什麼,而不是看源代碼。 –