How to add users to mongoDB when new user's sign in

In case anyone is finding this recently - here is a working snippet. Add this to an Action in Auth0 as described here: Write Your First Action

/**
 * @param {Event} event - Details about newly created user.
 */

const { MongoClient } = require("mongodb");

exports.onExecutePostUserRegistration = async (event) => {
  const newUser = { sub: event.user.sub };
  const client = await MongoClient.connect(event.secrets.MONGO_DB);
  const db = client.db();
  await db.collection("users").insertOne(newUser);
  client.close();
};

The user registration process will create an entry in your MongoDB database.

Cheers!

1 Like