Skip to content

Instantly share code, notes, and snippets.

@phiniezyc
Created December 14, 2021 07:35
Show Gist options
  • Save phiniezyc/f73bf819217252daf29168abb5d99f6b to your computer and use it in GitHub Desktop.
Save phiniezyc/f73bf819217252daf29168abb5d99f6b to your computer and use it in GitHub Desktop.
Auth0 Action to Save User in MongoDB
const { MongoClient } = require('mongodb');
/**
* Handler that will be called during the execution of a PostUserRegistration flow.
*
* @param {Event} event - Details about the context and user that has registered.
*/
exports.onExecutePostUserRegistration = async (event) => {
let uri = event.secrets.MONGODB_URI;
let dbName = event.secrets.MONGODB_DB;
let cachedClient = null;
let cachedDb = null;
const { db } = await connectToDatabase();
const newUser = event.user;
const result = await db.collection('user').insertOne(newUser);
async function connectToDatabase() {
if (cachedClient && cachedDb) {
return { client: cachedClient, db: cachedDb };
}
const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = await client.db(dbName);
cachedClient = client;
cachedDb = db;
return { client, db };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment