正如"Collections集合"一章中已经讨论的那样,无涯教程所有的数据都可以在客户端获得,这是一个安全问题,可以使用发布和订阅方法来处理。
在此示例中,无涯教程将使用 PlayersCollection 集合以及以下数据,在能够专心于本章本身之前,无涯教程已经准备好了此系列。如果不确定如何在Meteor应用程序中创建MongoDB集合,请查看无涯教程的集合一章。
为了保护无涯教程的数据,无涯教程需要删除允许无涯教程在客户端使用数据的 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()方法,此方法会将数据发送到客户端。
为了能够在客户端接收和使用该数据,无涯教程将创建 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);
无涯教程可以看到无涯教程的数据同时记录在开发者控制台和命令提示符窗口中。
无涯教程还可以发布部分数据。在此示例中,无涯教程使用 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 。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)