MeteorJS:在客户端获取用户档案

时间:2017-04-14 18:45:01

标签: reactjs meteor

所以,这个问题已经有了很好的记录,但在这里,我再次陷入困境......

在服务器端,我发布了:

Meteor.publish('userData', function(){ if (!this.userId) { return null; } 
return Meteor.users.find({}, {fields: {'profile': 1}}); });

在客户端路由器订阅上,我有:

this.register('userData', Meteor.subscribe('userData'));

然后在我的客户端代码中,我有:

if (Meteor.userId()) {
  var profile = Meteor.users.find(Meteor.userId()).profile;
  console.log(profile); // I keep getting undefined...

我没有使用autopublish或不安全的软件包。

我在mongodb集合中的数据如下:

{"_id" : "...", profile: { "password" : { "network" : "...", "picture" : "none" } }

我的错误说:

Uncaught TypeError: Cannot read property 'password' of undefined

思想?

4 个答案:

答案 0 :(得分:1)

用户配置文件会自动发布到客户端,您无需编写自定义发布来发送它。这就是为什么你永远不应该在配置文件中存储敏感的用户信息。你可以摆脱那个出版物。

要访问组件中的配置文件,您只需将组件(或整个应用程序)包装在将配置文件发送到组件的数据容器中。你这样做的原因是容器是被动的,所以组件将加载直到流星用户对象准备好,然后你可以立即访问存储在配置文件中的东西。

创建容器:

import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Navigation } from '/imports/ui/components/user-navigation/Navigation';

export default createContainer(() => {
    const loading = !Meteor.user();
    const user = Meteor.user();
    return { loading, user };
}, Navigation);

访问组件中的个人资料:

import React, { Component } from 'react';

export class Navigation extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        const { user, loading } = this.props;
        return (

            loading ? <Loading /> :

            <div className="navigation">
                User's name is: { user.profile.firstname }
            </div>
        )
    }
};

答案 1 :(得分:0)

我认为问题在于查询

var profile = Meteor.users.find({_id: Meteor.userId()}).profile;

或者这也应该起作用

var profile = Meteor.user().profile;

答案 2 :(得分:0)

因此,事实证明,我的大多数代码都是正确的,但正如上面指出的ghybs,我仍然需要等待用户数据。所以,这是我的工作代码:

// in publish.js on the server
Meteor.publish('userData', function(){ if (!this.userId) { return null; } 
return Meteor.users.find({_id: this.userId}, {fields: {'profile': 1}}); });

// in routes.jsx using FlowRouter
// after importing all the module external data
FlowRouter.route('/',{subscriptions:function(){
  this.register('getUser', Meteor.subscribe('userData'));
}, action() {
  mount(...etc...

// Keep in mind that I am using TrackerReact NPM to handle re-renders...
// in my component
if (FlowRouter.subsReady("getUser")) {
  // this returns an array with one object
  var userObject = Meteor.users.find({_id: Meteor.userId()}).fetch()[0];

答案 3 :(得分:0)

尝试替换

var profile = Meteor.users.find({_id: Meteor.userId()}).profile;

var profile = Meteor.users.findOne({_id: Meteor.userId()}).profile;
相关问题