Mongo DB Sample Code - Asynchronous

Overview

This article explains why newer versions of Mongo DB 5.x.x will encounter errors when using the sample code provided by Auth0 and provides alternate code.

Applies To

  • Custom Database Connections
  • MongoDB

Cause

Newer versions of Mongo run on asynchronous code.

Solution

The following async code sample can be used as a login script for the newer Mongo versions:

function getByEmail(email, callback) {
  const MongoClient = require('mongodb').MongoClient;
  const client = new MongoClient(configuration.URL);
  
  (async () => {
    try {
      await client.connect();
      
      const db = client.db(configuration.DB);
      const users = db.collection('users');
      
      const user = await users.findOne({ email: email });
      if (!user) return callback(null, null);
      
      return callback(null, {
        user_id: user._id.toString(),
        nickname: user.nickname,
        email: user.email
      });
    } catch(e) {
      return callback(e);
    } finally {
      await client.close();
    }
  })();
}