Node18 Environment and MongoDB Do Not Work
Last Updated:
Overview
Node18 environment and MongoDB do not work with the supported 5.1 and 5.7 MongoDB drivers. The call to the Database (DB) hangs and eventually times out. This article will explain why and provide a solution.
Applies To
- Node18
- MongoDB Version 5.1 and 5.7
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
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();
}
})();
}