Meteor:注册用户然后自动登录

时间:2017-08-16 18:01:39

标签: meteor account meteor-accounts

我有一份参与在线实验的同意书。一旦参与者同意同意表,我想为他们创建一个用户帐户并将其添加到玩家集合中。我不希望用户选择他们的用户名(如果没有密码我更喜欢)。界面中不应该有登录/注册,它都是自动完成的。我目前的代码:

consent_page.js包含以下代码:

import './consent_page.html';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Template } from 'meteor/templating';
import { Meteor } from 'meteor/meteor'

Template.consent_page.events({
    'submit .consent-form'(event) {
        event.preventDefault();
        Meteor.call('players.addPlayer');
        FlowRouter.go('/instructions')
    }
});

被调用的players.addPlayer方法是:

import { Meteor } from 'meteor/meteor';
import { Players } from './players.js';
import { Random } from 'meteor/random'
import { Accounts } from 'meteor/accounts-base';

Meteor.methods({
    'players.addPlayer'() {
        console.log('I am in the method');
        const random_username = Random.id();
        const random_password = Random.id();
        user = Accounts.createUser({
            username: random_username,
            password: random_password
        });

        Players.insert({
            _id: this.userId,
            enterTime: new Date(),
            status: 'instructions',
            passedQuiz: false,
            quizAttempts: 0,
            needRematch: false,
            condition: 'control',
            consent: true
        });

        if (user){
            return user
        } else {
            console.log('no user')
        }
    }
});

但是,这似乎不会自动登录用户,因为我收到以下错误:

I20170816-13:57:59.061(-4)? I am in the method
I20170816-13:57:59.248(-4)? Exception while invoking method 'players.addPlayer' Error: Meteor requires document _id fields to be non-empty strings or ObjectIDs
I20170816-13:57:59.248(-4)?     at [object Object].insert (packages/mongo/collection.js:478:13)
I20170816-13:57:59.249(-4)?     at [object Object].Meteor.methods.players.addPlayer (imports/api/players/methods.js:17:17)
I20170816-13:57:59.250(-4)?     at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1768:12)
I20170816-13:57:59.250(-4)?     at packages/ddp-server/livedata_server.js:719:19
I20170816-13:57:59.251(-4)?     at [object Object].EVp.withValue (packages/meteor.js:1135:15)
I20170816-13:57:59.251(-4)?     at packages/ddp-server/livedata_server.js:717:46
I20170816-13:57:59.251(-4)?     at [object Object].EVp.withValue (packages/meteor.js:1135:15)
I20170816-13:57:59.252(-4)?     at packages/ddp-server/livedata_server.js:715:46
I20170816-13:57:59.252(-4)?     at [object Object]._.extend.protocol_handlers.method (packages/ddp-server/livedata_server.js:689:23)
I20170816-13:57:59.252(-4)?     at packages/ddp-server/livedata_server.js:559:43

问题是this.userId返回null。如果我用其他内容替换_id中的Players.insert(..),我可以在mongodb中看到用户被添加到用户集合和玩家集合中。

如何在创建帐户时建立连接/登录用户,以便我可以立即使用this.userId?我可以禁用密码吗?

1 个答案:

答案 0 :(得分:0)

您在服务器上运行此操作,因此用户不会自动登录。当您尝试引用它来创建播放器时,this.userId将不确定。

您需要从客户端调用Accounts.createUser(),然后调用该方法将回调中的玩家插入createUser()