How to hook user insert using Accounts package

Hello!
Is it possible to intercept a user insertion by Accounts.createUserAsync in a similar way below?

class MongoUserCollection extends Mongo.Collection<Meteor.User> {
  insert(doc, callback) {   
    const docId = super.insert(list, callback);
    sendEmail(docId, doc.profile.name, doc.emails[0].address);
  }
}

export UserCollection = new MongoUserCollection('users');

I could’t make it work because the users collection already exists.

I also tried to use meteor/matb33:collection-hooks but can import as suggested on documentation:

import { CollectionHooks } from 'meteor/matb33:collection-hooks';

But it shows the error: Module '"meteor/matb33:collection-hooks"' has no exported member 'CollectionHooks'..

Suggestions?

Isn’t this what you are looking for? Accounts (multi-server) | Meteor API Docs

1 Like

Hi, thanks for answering.
However, I can’t see how it could help with my question, can you provide an example ou explanation?

Hey @marcuslma, the documentation shared by @paulishca could be helpful because the Accounts.onCreateUser() function is called whenever a new user is created.

To test this function, create a new file called accounts.js and import it into your main.js file:

import { Accounts } from 'meteor/accounts-base';

Accounts.onCreateUser((options, user) => {
  console.log('onCreateUser');
  console.log(options, user);
  //  Add your logic to send the email here
});

I added some console.log() statements so you can test it and see how it works. Now, when you insert a new user, the onCreateUser() function above will be called, and you can add your email sending logic inside it.

1 Like

Hi @fredmaiaarantes
I’m using Accounts.onCreateUser to put extra data on my users.
But I’m not sure about something, this is called before or after user insertion?
Because what I need to do is send a welcome email on user insertion.

Accounts.validateNewUser runs after Accounts.onCreateUser but to make sure the account has been created, you can trigger email sending on Accounts.onLogin event, you will need a flag to mark which account you sent welcome email already.

Hi @minhna
The email must be sent on at the time the user get inserted, because the email contains instructions and a first time login page link.

Besides that, depending on the user type, the sent email is different, so I must make a decision based on the inserted user.

So I think your idea not fit with my needs, but thanks for your suggestion.