Meteor - 发布和订阅
正如在集合章节中讨论的那样,我们的所有数据都可以在客户端使用。这是一个安全问题,可以使用发布和订阅方法处理。
删除自动发布
在此示例中,我们将使用包含以下数据的 PlayersCollection 集合。我们之前准备好了这个集合,以便能够专注于章节本身。如果您不确定如何在 Meteor 应用中创建 MongoDB 集合,请查看我们的 集合 章节。

为了保护我们的数据,我们需要删除允许我们在客户端使用数据的 autopublish 包。
C:\Users\username\Desktop\meteorApp>meteor remove autopublish
完成此步骤后,我们将无法从客户端获取数据库数据。我们只能在命令提示符窗口中从服务器端查看它。查看以下代码 −
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 = "John"。
var PlayersCollection = new Mongo.Collection('playersCollection'); if(Meteor.isServer) { Meteor.publish('allowedData', function() { return PlayersCollection.find({name: "John"}); }) } if (Meteor.isClient) { Meteor.subscribe('allowedData'); }; Meteor.setTimeout(function() { myLog = PlayersCollection.find().fetch(); console.log(myLog); }, 1000);
一旦我们运行此代码,命令提示符将记录所有数据,而客户端控制台将只记录两个名为John的对象。
