流星:注册用户,然后自动登录
问题描述:
我有一个参与在线实验的同意书。一旦参与者同意同意书,我想为他们创建一个用户帐户并将其添加到Players集合中。我不希望用户选择他们的用户名(如果没有密码,我更喜欢)。界面中不应该有登录/注册,全部自动完成。我当前的代码:流星:注册用户,然后自动登录
的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。如果我用其他东西替换Players.insert(..)
中的_id
,我可以在mongodb中看到用户被添加到用户集合和玩家集合中。
我如何建立连接/登录用户创建他们的帐户,所以我可以立即使用this.userId?我可以禁用密码吗?
答
您正在服务器上运行此操作,因此用户不会自动登录。当您尝试引用它来创建播放器时,this.userId
将不确定。
您需要从客户端调用Accounts.createUser()
,然后调用该方法将播放器从回调中插入到createUser()
。
我有点需要帐户包,以便与用户状态包一起工作https://github.com/mizzao/meteor-user-status跟踪用户闲置,关闭他们的浏览器等。 – amaatouq
另外,看起来,当客户端重新连接到服务器(在暂时失去连接之后)时,它将获得具有新连接ID的新连接。我希望能够知道是否有人回来。 – amaatouq