Meteor - 发布和订阅

Meteor - 发布和订阅 首页 / Meteor入门教程 / Meteor - 发布和订阅

正如"Collections集合"一章中已经讨论的那样,无涯教程所有的数据都可以在客户端获得,这是一个安全问题,可以使用发布和订阅方法来处理。

删除自动发布

在此示例中,无涯教程将使用 PlayersCollection 集合以及以下数据,在能够专心于本章本身之前,无涯教程已经准备好了此系列。如果不确定如何在Meteor应用程序中创建MongoDB集合,请查看无涯教程的集合一章。

Meteor Publish and Subscribe Database Data

为了保护无涯教程的数据,无涯教程需要删除允许无涯教程在客户端使用数据的 autopublish 软件包。

C:\Users\username\Desktop\meteorApp>meteor remove autopublish

完成此步骤后,无涯教程将无法从客户端获取数据库数据,无涯教程只能在命令提示符窗口中从服务器端看到它。

链接:https://www.learnfk.comhttps://www.learnfk.com/meteor/meteor-publish-subscribe.html

来源:LearnFk无涯教程网

meteorApp.js

var PlayersCollection = new Mongo.Collection('playersCollection');
var myLog = PlayersCollection.find().fetch();
console.log(myLog);

命令提示符窗口将显示带有四个对象的整个集合,而开发者控制台将显示一个空数组。现在无涯教程的应用程序更加安全。

Meteor Publish and Subscribe Autopublish Removed

使用发布和订阅

假设无涯教程要允许客户使用无涯教程的数据,为此,无涯教程需要在服务器上创建 Meteor.publish()方法,此方法会将数据发送到客户端。

为了能够在客户端接收和使用该数据,无涯教程将创建 Meteor.subscribe()方法,在示例的最后,无涯教程正在搜索数据库,此代码在客户端和服务器端均运行。

var PlayersCollection = new Mongo.Collection('playersCollection');

if(Meteor.isServer) {

   Meteor.publish('allowedData', function() {
      return PlayersCollection.find();
   })
}

if (Meteor.isClient) {
   Meteor.subscribe('allowedData');
};

Meteor.setTimeout(function() {
   var myLog = PlayersCollection.find().fetch();
   console.log(myLog);
}, 1000);

无涯教程可以看到无涯教程的数据同时记录在开发者控制台和命令提示符窗口中。

Meteor Publish and Subscribe Allowed All

过滤客户端数据

无涯教程还可以发布部分数据。在此示例中,无涯教程使用 name =" Learnfk" 发布数据。

var PlayersCollection = new Mongo.Collection('playersCollection');

if(Meteor.isServer) {

   Meteor.publish('allowedData', function() {
      return PlayersCollection.find({name: "Learnfk"});
   })
}

if (Meteor.isClient) {
   Meteor.subscribe('allowedData');
};

Meteor.setTimeout(function() {
   myLog = PlayersCollection.find().fetch();
   console.log(myLog);
}, 1000);

一旦运行此代码,命令提示符将记录所有数据,而客户端控制台将仅记录两个名称为 Learnfk 。

Meteor Publish and Subscribe Allowed All

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入剖析Kubernetes -〔张磊〕

如何设计一个秒杀系统 -〔许令波〕

面试现场 -〔白海飞〕

Linux实战技能100讲 -〔尹会生〕

软件设计之美 -〔郑晔〕

A/B测试从0到1 -〔张博伟〕

说透低代码 -〔陈旭〕

商业思维案例笔记 -〔曹雄峰〕

结构写作力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)