您如何有条件地将数据发送到Meteor中的客户端? [英] How do you conditionally send data to the client in Meteor?

查看:93
本文介绍了您如何有条件地将数据发送到Meteor中的客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图弄清楚如何通过 meteor 有条件地向客户端发送数据。我有两种用户类型,根据用户的类型,它们在客户端上的接口(因此它们所需的数据是不同的)。

I'm trying to figure out how to conditionally send data to the client in meteor. I have two user types, and depending on the type of user, their interfaces on the client (and thus the data they require is different).

让我们说用户是键入辅导员学生。每个用户文档都有角色:'counselor'角色:'student'

Lets say users are of type counselor or student. Every user document has something like role: 'counselor' or role: 'student'.

学生有学生特定信息,如 sessionsRemaining 辅导员和辅导员有类似 pricePerSession 等的东西。

Students have student specific information like sessionsRemaining and counselor, and counselors have things like pricePerSession, etc.

我如何确保客户端的Meteor.user()有我需要的信息,没有额外的信息吗?如果我以学生身份登录, Meteor.user()应包含 sessionsRemaining 辅导员,但如果我以辅导员的身份登录,则不会。我认为我可能正在寻找的是有条件的出版物和流星术语中的订阅。

How would I make sure that Meteor.user() on the client side has the information I need, and none extra? If I'm logged in as a student, Meteor.user() should include sessionsRemaining and counselor, but not if I'm logged in as a counselor. I think what I may be searching for is conditional publications and subscriptions in meteor terms.

推荐答案

使用字段选项只返回Mongo查询所需的字段。

Use the fields option to only return the fields you want from a Mongo query.

Meteor.publish("extraUserData", function () {
  var user = Meteor.users.findOne(this.userId);
  var fields;

  if (user && user.role === 'counselor')
    fields = {pricePerSession: 1};
  else if (user && user.role === 'student')
    fields = {counselor: 1, sessionsRemaining: 1};

  // even though we want one object, use `find` to return a *cursor*
  return Meteor.users.find({_id: this.userId}, {fields: fields});
});

然后在客户端上只需致电

And then on the client just call

Meteor.subscribe('extraUserData');

Meteor中的订阅可能会重叠。因此,这种方法的优点在于,向客户端提供额外字段的发布功能与Meteor的幕后发布功能一起工作,该功能发送基本字段,如用户的电子邮件地址和配置文件。在客户端上, Meteor.users 集合中的文档将是两组字段的并集。

Subscriptions can overlap in Meteor. So what's neat about this approach is that the publish function that ships extra fields to the client works alongside Meteor's behind-the-scenes publish function that sends basic fields, like the user's email address and profile. On the client, the document in the Meteor.users collection will be the union of the two sets of fields.

这篇关于您如何有条件地将数据发送到Meteor中的客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆