Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - How can I limit which fields are published to the client?

Tags:

meteor

I want to publish only a limited amount of data to the client.

I've tried to do it like this:

# server
Meteor.publish('users', ->
  Meteor.users.find({},
    fields:
      services: 0
  )
)

But the client still receives the whole object.

# client
Meteor.startup( ->
  Meteor.subscribe('users')
)

# ... 
# in another function
Meteor.users.find().observe( ->
  changed: (updated) ->
    console.log updated
)

What am I doing wrong?

like image 366
peter Avatar asked Oct 09 '12 03:10

peter


People also ask

How does Meteor publishing work?

In Meteor a publication is a named API on the server that constructs a set of data to send to a client. A client initiates a subscription which connects to a publication, and receives that data.

What does Meteor Subscribe do?

The Meteor. publish function is used on the server to define what data should be available to users of the application. The Meteor. subscribe function is used on the client to retrieve the data that's published from the server.

Is Meteorjs secure?

In a Meteor app, things are pretty simple: Code that runs on the server can be trusted. Everything else: code that runs on the client, data sent through Method and publication arguments, etc, can't be trusted.


2 Answers

Meteor.publish '', ->
    Posts.find({}, { fields: { title: 1, content: true, secret: false } });

what about add those {}

like image 50
crapthings Avatar answered Sep 30 '22 03:09

crapthings


The code below works for me (coffeescript). The pwd field isn't published.

Server

Meteor.publish "users", (userId) ->
  user = Users.find userId,
    fields:
      pwd: false

  return user

Client

Meteor.autosubscribe ->
    userId = Session.get SESSION_USER

    Meteor.subscribe 'users', userId

The only differences I see are

  • 0 vs false... (should be a matter of taste, only)
  • Your collection is accessed via Meteor
  • In the client my subscription is placed inside a autosubscribe callback while you're using the observe method.

Do the fields exists in the result of Meteor.users.find().fetch() in the browsers console, too?

like image 31
Andreas Avatar answered Sep 30 '22 03:09

Andreas