微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Meteor.user 与客户端上的附加字段

如何解决Meteor.user 与客户端上的附加字段

在 Meteor 中,可以像这样向新用户文档的根级别添加其他字段:

// See: https://guide.meteor.com/accounts.html#adding-fields-on-registration
Accounts.oncreateuser((options,user) => 
  // Add custom field to user document...
  user.customField = "custom data";

  return user;
});

在客户端,可以像这样检索有关当前用户的一些数据:

// { _id: "...",emails: [...] }
Meteor.user()

认情况下,返回的用户上不存在 customField。如何通过 Meteor.user() 调用检索该附加字段,从而获得 { _id: "...",emails: [...],customField: "..." }?目前,publishing custom data 上的文档似乎建议发布一个额外的集合。由于代码和流量的开销,这是不希望的。可以覆盖 Meteor.user() 调用认字段以提供其他字段吗?

解决方法

您有几个解决方案可以用来解决这个问题。

  1. 空发布
Meteor.publish(null,function () {
  if (this.userId !== null) {
    return Meteor.users.find({ _id: this.userId },{ fields: { customField: 1 } });
  } else {
    return this.ready();
  }
},{ is_auto: true });

这将为您提供所需的结果,但也会导致额外的数据库查找。虽然这不是由 _id 决定的并且非常有效,但我仍然认为这是不必要的开销。

2.更新 Meteor 默认为用户发布的字段。

Accounts._defaultPublishFields.projection = { customField: 1,...Accounts._defaultPublishFields.projection };

这必须在任何 Meteor.startup 块的外部运行。如果在一个内运行,这将不起作用。此方法不会导致对数据库的额外调用,并且是我完成此操作的首选方法。

,

您实际上误解了文档。它不建议填充和发布单独的集合,只是一个单独的出版物。那不一样。您可以拥有多个出版物/订阅,它们都提供相同的集合。所以你需要做的就是:

服务器:

Meteor.publish('my-custom-user-data',function() {
  return Meteor.users.find(this.userId,{fields: {customField: 1}});
});

客户:

Meteor.subscribe('my-custom-user-data');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。