MeteorJS:在客户端获取用户配置文件

IT技术 reactjs meteor
2021-05-23 09:05:01

所以,这个问题已经被很好地记录在案,但我在这里,再次卡住了......

在服务器端,我已经发布:

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...

我没有使用自动发布或不安全的包。

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

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

我的错误说:

Uncaught TypeError: Cannot read property 'password' of undefined

想法?

4个回答

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

要访问组件中的配置文件,您需要做的就是将您的组件(或整个应用程序)包装在将配置文件发送到组件的数据容器中。这样做的原因是容器是react式的,因此组件将加载,直到meteor 用户对象准备就绪,然后您就可以立即访问存储在配置文件中的内容。

创建容器:

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>
        )
    }
};

所以,事实证明,我的大部分代码都是正确的,但正如 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];

尝试更换

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

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

我认为问题出在查询上

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

或者这也应该有效

var profile = Meteor.user().profile;