onCreateUser creates user before adding custom field

Hello,
I just found that the onCreateUser method seems to create the user before actually adding my user.chat field I declare inside the callback function from ChatChannels (i do this because I need the id of the just created channel).

I placed some console.log and I found out that the one before the return statement is executed before the one after the user.chat declaration. Is this a bug or and expected behaviour? How can I add my field?

Accounts.onCreateUser(function (options, user) {

    Projects.insert(
       {
            name: options.project.projName, 
            domain: options.project.projPath,
            owner: user._id
        }, function (err, projId) {

            ChatChannels.insert(
                {
                    name: 'general', 
                    project_id: projId
                }, function (err, channelId) {
                    user.chat = {channel : channelId};
                    console.log('chat field added');
                });
            ChatChannels.insert(
                {
                    name: 'offtopic', 
                    project_id: projId});
                });

    // We still want the default hook's 'profile' behavior.
    if (options.profile) {
        user.profile = options.profile;
    }

    console.log('User Created')
    return user;
});

Thank you

1 Like

It sounds like a chicken and egg problem. onCreateUser completes before your callback is finished. If you want the callback to execute first, insert your channel before creating the user and update it after the user is created w/the user id. Alternatively, wrap your call.

1 Like