English 中文(简体)
Meteor - Publish & Subscribe
  • 时间:2024-09-08

Meteor - Pubpsh and Subscribe


Previous Page Next Page  

As already discussed in the Collections chapter, all of our data is available on the cpent side. This is a security issue that can be handled with pubpsh and subscribe methods.

Removing Autopubpsh

In this example, we will use PlayersCollection collection with the following data. We prepared this collection before to be able to concentrate on the chapter itself. If you are unsure how to create MongoDB collections in meteor app, check our collections chapter.

Meteor Pubpsh and Subscribe Database Data

To secure our data, we need to remove autopubpsh package that was allowing us to use the data on the cpent side.

C:UsersusernameDesktopmeteorApp>meteor remove autopubpsh

After this step, we will not be able to get the database data from the cpent side. We will only be able to see it from the server side in the command prompt window. Checkout the following code −

meteorApp.js

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

The command prompt window will show the entire collection with four objects, while the developers console will show an empty array. Now our app is more secure.

Meteor Pubpsh and Subscribe Autopubpsh Removed

Using Pubpsh and Subscribe

Let s say we want to allow the cpents to use our data. For this, we need to create Meteor.pubpsh() method on the server. This method will send the data to the cpent.

To be able to receive and use that data on the cpent side, we will create Meteor.subscribe() method. At the end of the example, we are searching the database. This code is running on both the cpent and the server side.

var PlayersCollection = new Mongo.Collection( playersCollection );

if(Meteor.isServer) {

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

if (Meteor.isCpent) {
   Meteor.subscribe( allowedData );
};

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

We can see that our data is logged in both the developers console and the command prompt window.

Meteor Pubpsh and Subscribe Allowed All

Filtering Cpent Data

We can also pubpsh part of the data. In this example, we are pubpshing data with name = "John".

var PlayersCollection = new Mongo.Collection( playersCollection );

if(Meteor.isServer) {

   Meteor.pubpsh( allowedData , function() {
      return PlayersCollection.find({name: "John"});
   })
}

if (Meteor.isCpent) {
   Meteor.subscribe( allowedData );
};

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

Once we run this code, the command prompt will log all of the data, while the cpent side console will just log two objects with the name John.

Meteor Pubpsh and Subscribe Allowed All Advertisements