简体   繁体   中英

Meteor: Different user count on server and client

Why do I get different results for all users on client and server side? On client side it is always 1. Does it matter if I'm logged in? And if this is the case, how can I get all data while I'm logged in?

Console Server: Users.find().count() = 7
Console Client: Users.find().count() = 1

shared/collections.js

Users = Meteor.users;

client/router.js

Router.route('/users', {
    name: 'users',
    data: function() {
         return {
            usersAll: Users.find({})
         }
    }
});

template

<template name="users">
    <ul class="list">
        {{#each usersAll}}
            <li><a href="/user/{{_id}}">{{profile.name}}</a></li>
        {{/each}}
    </ul>
</template>

In the template I just get one result.

Yes, it does matter that you are logged in. You have to publish and subscribe to data on the client. If you attempt to do Meteor.users.find() on the client, you will always return the currently active user. (if any)

If you do Meteor.users.find() on the server you will return ALL users, regardless of the publication/subscription. It's a security precaution, to keep regular users from accessing private information on the client.

You can publish more or less data to the client if you choose. Check this article out: https://www.meteor.com/tutorials/blaze/publish-and-subscribe

Or the documentation: http://docs.meteor.com/#/full/meteor_publish

You can always add the autopublish package if you want to publish all data. This is not recommended for production apps though.

Server

Meteor.publish('allUsers', function(){
    return Meteor.users.find();
});

Client

Template.users.onCreated(function(){
    var instance = this;

    instance.autorun(function(){
         var allUsers = instance.subscribe('allUsers');
    });
});

Template.users.helpers({
    'usersAll': function(){
        return Meteor.users.find().fetch();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM