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

查看:7
本文介绍了在 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).

假设用户属于 counselorstudent 类型.每个用户文档都有类似 role: 'counselor'role: 'student' 的内容.

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

学生有学生特定的信息,如sessionsRemainingcounselor,而辅导员有pricePerSession 等信息.

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

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

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.

推荐答案

使用 fields 选项可以只从 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});
});

然后在客户端调用

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天全站免登陆