Meteor - 为什么我应该尽可能使用 this.userId 而不是 Meteor.userId()?

Meteor - Why should I use this.userId over Meteor.userId() whenever possible?

根据 David Glasser 在 GitHub 期中的 this comment 判断:

this.userId is the primary API and Meteor.userId() is syntactic sugar for users new to JavaScript who might not understand the details of successfully using this yet

似乎我们应该尽可能使用 this.userId(例如在方法函数中,您可以同时使用两者),并且只在发布函数中使用 Meteor.userId()。如果这个假设是正确的,为什么?

(参考代码的相关位也有帮助,我似乎找不到)

简单来说,Meteor.userId()每次使用时都会查询数据库。在客户端(逻辑上),它看起来不错——因为我们有 minimongo。

在服务器端,使用 Meteor.userId() 会消耗服务器上的额外资源,这有时是不希望的。

现在,this.userId 更像是一个会话变量,即只有当当前会话附加了一个用户 ID 时,它才会有一个值。因此,使用 'this' 引用不会每次都去获取数据库,而是使用活动会话用户 ID。

将性能视为一个因素。这是使用 this.userId 而不是 Meteor.userId

的主要原因

您的问题似乎混淆了 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) stored in a particular 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 包)。