当用户从使用useraccounts:core
包生成的表单注册(第一个用户)时,我们如何自动创建第二个用户?
从Accounts.createUser
内运行Accounts.onCreateUSer
会导致错误Exception while invoking method 'ATCreateUserServer' TypeError: Cannot read property '_id' of undefined
Accounts.onCreateUser(function(options, user) {
// Create Primary User
if(!user.type) {
// Set user.type as 'user'
user.type = 'user'
// Create Secondary User
Accounts.createUser({
username: options.profile.slaveName,
password: options.profile.slaveName,
type: 'slave',
profile: {
firstName: user.profile.firstName,
lastName: user.profile.lastName
}
})
user.profile = options.profile
return user
}
// Create Secondary User
if(user.type == 'slave') {
user.profile = options.profile
return user
}
});
答案 0 :(得分:3)
在我看来,你正在混淆user
参数和options
参数。例如,type
字段通过options
参数进入,而不是user
。
以下代码对我有用:
Accounts.onCreateUser(function(options, user) {
// Create Primary User
if(!options.type) {
// Set user.type as 'user'
options.type = 'user'
// Create Secondary User
Accounts.createUser({
username: options.profile.slaveName,
password: options.profile.slaveName,
type: 'slave',
profile: {
firstName: options.profile.firstName,
lastName: options.profile.lastName
}
});
user.profile = options.profile
return user
}
// Create Secondary User
if(options.type == 'slave') {
user.profile = options.profile
return user
}
});
然后,我接受了测试:
// console
Accounts.createUser({username: "guest", password: "guest", profile: {slaveName: 'guestslave', firstName: "Greatest", lastName: "Ever"}})
Meteor.users.find({username: {$regex: 'guest'}}).fetch()
> [returned two user objects]