Meteor 用户帐户的自定义字段和全局订阅

Custom fields and global subscriptions for Meteor user accounts

我是第一次向 Meteor 用户帐户添加自定义数据。我已经能够毫不费力地添加自定义字段,而且我知道它们在那里,因为我可以在 Mongol 中看到它们。我通过全球订阅发布,那么我该如何从各个领域读取数据?看起来语法与使用 publish/subscribe 方法时的语法有很大不同。

所以,我有这样的用户帐户(如在蒙古语中所见):

"_id": "#################",
  "profile": {
    "name": "Test User"
  },
  "customfields": {
    "customfield1": [
      "A","B","C"
    ]
  }
}

server/main.js我有以下

Meteor.publish(null, function() {
  return Meteor.users.find(this.userId, {fields:{customfields:1}});
});

这似乎发布得很好。但是我使用什么代码将光标呈现为数据呢?我一直在 client/main.js 中使用这样的代码变体,但没有成功:

var stuff = Meteor.users.find(this.userId).fetch();
console.log(stuff.customfield1);

感谢任何帮助。

由于 customfield1 嵌套在 customfields 中,您尝试过 stuff.customfields.customfield1 吗?

MyCollection.find() return是一个光标MyCollection.findOne() return是一个对象,即单个 mongodb 文档。

一个出版物 必须 return一个光标游标数组。你的发布没问题。

您基本上是在尝试使用户对象的 customfields 键在客户端可见。 (profile 密钥由 Meteor 自动发布)。

在客户端,你在做什么:

var stuff = Meteor.users.find(this.userId).fetch();

您可以简单地使用:

var stuff = Meteor.user();

var stuff = Meteor.users.findOne(Meteor.userId());

然后 stuff.customfields 将包含您要查找的内容。

除非您正在寻找与登录用户不同的用户,否则第二种形式对我来说太冗长了。

注意:客户端的this.userId不是当前用户的userId,它将 未定义。这只适用于服务器。这实际上可能是您问题的根本原因。此外,您的出版物必须 ready() 才能使用数据。例如,登录后不是立即如此。