2012-11-24 50 views
8

根據流星文檔,如果安裝了autopublish軟件包,則應將所有用戶發佈給所有客戶端。使用流星列出客戶端上的所有用戶

http://docs.meteor.com/#meteor_users

我已經安裝了包自動發佈,但使用上Meteor.usersforEach只列出當前登錄的用戶。

是否有更正確的方式來使用coffeescript列出客戶端上的所有用戶?

+0

這是文檔中的錯誤嗎?有一個相關的封閉問題https://github.com/meteor/meteor/issues/517 – amirnissim

回答

8

,如果你自動發佈用戶收集,而不使用訂閱

if Meteor.isServer 

    Meteor.publish null, -> 
     Meteor.users.find {}, 
      fields: 
       username: 1 
       profile: 1 

,如果你想訂閱指定用戶可以

if Meteor.isServer 

    Meteor.publish 'users-by-selector', (options) -> 
     Meteor.users.find options, # options as selector like $in: name: 'john' 
      fields: # use fields to only publish specify fields you want to send. 
       username: 1 
       profile: 1 

if Meteor.isClient 

    Meteor.autosubscribe -> 
     options = Session.get 'your mongodb selector' 
     Meteor.subscribe 'users-by-selector', options, -> 
      console.log 'on Subscribe Complete Callback.' 
      if Meteor.users.find().count() 
       Session.set 'specifyUsersLoaded', true 
+0

你的第一個代碼片段工作,雖然我不得不在''fields:「下添加''emails:1'',所有用戶的'username''和''profile''都是空的。顯然用戶不會自動發佈,除非其自動發佈的字段中有值。 – danielsvane

+0

我沒有找到@danielsvane提到的限制。不過,需要注意的一點是,不同的提供程序包提供了不同的數據結構。這在你思考時很有意義,但如果你沒有做好準備,這可能會令人困惑。上面的@crapthings代碼(包括'profile'和'username')可以很好地獲取Facebook和'accounts-password'包的用戶名。要從'user'記錄中獲取用戶名,您需要'user.username || user.profile.name'。 – rdickert

+29

偉大且有用的答案+1,但假設CoffeeScript爲-1。問題未被標記爲CoffeeScript。它不叫Meteor.coffee –

9

這裏是流星的Parties example的摘錄:

// in server.js 
Meteor.publish("directory", function() { 
    return Meteor.users.find({}, {fields: {emails: 1, profile: 1}}); 
}); 

// in client.js 
Meteor.subscribe("directory"); 
+0

這個例子不存在了,我如何迭代模板中的每個用戶? –

+1

它在這裏:https://github.com/meteor/meteor/tree/devel/examples/other/parties(代碼是相同的,更新的鏈接) – amirnissim