Node18 Environment and MongoDB Do Not Work

Overview

Node18 environment and MongoDB do not work with the supported 5.1 and 5.7 MongoDB drivers. The call to the DB hangs up and eventually times out.

Cause

One of the breaking changes in version 5 of the driver is that callbacks are no longer supported. Our Mongo DB templates for the Custom Database scripts use callbacks

  • The driver removes support for callbacks in favor of a promise-based API.

Solution

In order to use version 5 of the Mongo driver, update the script to use promises. Here is an example of the get user script:

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();
    }
  })();
}