2015-09-26 63 views
3

this comment由大衛·格拉瑟在GitHub上的問題來看:流星 - 爲什麼我應該儘可能使用this.userId通過Meteor.userId()?

this.userId是主要的API和Meteor.userId()是用戶新的JavaScript誰可能不明白成功地利用這個尚未

的細節語法糖

看來我們應該儘可能使用this.userId(例如在一個方法函數中,您可以同時使用這兩個函數),並且只在發佈函數中使用Meteor.userId()。如果這個假設是正確的,爲什麼

(參見代碼中的相關內容也將是有益的,我似乎無法找到它)

+1

的可能重複的[Meteor.userId VS Meteor.userId()](http://stackoverflow.com/questions/24320754/meteor-userid-vs-meteor-userid) – CollinD

+0

@CollinD這個問題是與問候到'Meteor.userId'和'Meteor.userId()'。這個問題是關於'this.userId' vs'Meteor.userId()' – dayuloli

+0

有一個似乎相關的答案。它特別引用你的問題。對不起,如果不是。 – CollinD

回答

6

您的問題似乎混淆了Meteor.userId()Meteor.user()。問題的主體似乎在詢問前者,而主題是詢問後者。我會盡力解決這兩個問題。

  1. 在服務器,發佈函數中,調用要麼Meteor.userId()Meteor.user()cause an error。相反,分別使用this.userIdMeteor.users.findOne(this.userId)。但是請注意,發佈功能僅在客戶訂閱時纔會調用。如果您希望在用戶記錄更改時更改發佈,則需要observe()Meteor.users.find(this.userId)返回的光標,並在記錄更改時採取適當的操作。
  2. 在服務器上,在處理方法調用時,Meteor.userId()Meteor.user()將分別對應主叫用戶的ID及其記錄。但是,請注意,致電Meteor.user()將導致數據庫查詢,因爲它們是essentially equivalent to Meteor.users.findOne(Meteor.userId())

    直接在方法調用中,您也可以使用this.userId而不是Meteor.userId(),但您不太可能看到顯着的性能差異。當服務器收到方法調用時,它將runs your method implementation with the user's ID (and some other info)存儲在光纖上的特定slot中。 Meteor.userId()只是從當前光纖上的插槽中檢索ID。這應該很快。

    重構使用Meteor.userId()而不是this.userId的代碼通常更容易,因爲您不能在方法體外部使用this.userId(例如,this在您從方法主體調用的函數內不會有'userId'屬性),並且您不能在客戶端上使用this.userId

  3. 在客戶端上,Meteor.userId()Meteor.user()不會拋出錯誤,this.userId不起作用。撥打Meteor.user()的電話號碼是essentially equivalent to Meteor.users.findOne(Meteor.userId()),但由於這對應於迷你mongo數據庫查詢,所以性能可能不會成爲問題。但是,出於安全原因,由Meteor.user()返回的對象可能不完整(特別是如果未安裝autopublish程序包)。
+0

感謝您的提問,我的意思是'Meteor.userId()',並已更正問題標題。你的回答中的一切都很清楚,並證實了我一直在閱讀的內容。是否有可能擴展一點「因爲Meteor.userId()將在調用堆棧中更深入地工作」?在你之前的評論中,你說過:「Meteor.userId()不會查詢數據庫或消耗任何重要的額外資源。」 - 那它是做什麼的?我一直無法在源代碼中找到這段代碼。 – dayuloli

+0

感謝您的編輯,儘管我無法理解您所鏈接的代碼,但我現在明白了'Meteor.userId()'的作用。還要感謝您對該問題的評論給出了另一種觀點,使用'Meteor.userId()'可能會更好,因爲您可以在其他地方(可能在客戶端)移植相同的代碼。再次感謝您的回答。 – dayuloli

2

簡單地說,Meteor.userId()查詢你所使用的數據庫每次。在客戶端(邏輯上),它看起來很好 - 因爲我們有minimongo。

在服務器端,使用Meteor.userId()會消耗SERVER上的額外資源,有時這是不受歡迎的。

現在,this.userId更像是一個會話變量,也就是說,它只有在當前會話附有用戶標識時纔會有值。因此,使用'this'引用不會每次都訪問數據庫,而不是使用活動會話userId。

將性能視爲一個因素。這是使用this.userId而不是Meteor.userId的主要原因

+0

從發佈函數調用Meteor.user或Meteor.userId會導致異常。即,除了發佈功能之外,這些可用於服務器的任何位置,而this.userid可在任何地方使用。此外,很明顯,Meteor.user Meteor.userId等從mongo中獲取用戶對象(通過Accounts對象) - 請參閱https://github.com/meteor/meteor/blob/devel/packages/accounts-base/accounts_common .js#L222 – Sak90

+1

'Meteor.userId()'不查詢數據庫或消耗任何重要的額外資源。但是,在服務器上,'Meteor.user()'會。 –

相關問題