DEV Community

Cover image for MongoDB: Connect to the Mongo Driver - Series #07
Functional Javascript
Functional Javascript

Posted on • Updated on

MongoDB: Connect to the Mongo Driver - Series #07


This is our lowest level code for establishing a connection to the Mongo database.

import { MongoClient } from "mongodb";
import env from "@root/mid-libs_node/bl/envs/processEnv";

const opt = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  connectTimeoutMS: 60000,

get a connection obj to atlas mongodb

@return {Promise<MongoClient> | null}
const mongoAsync = async () => {
  try {
    return await MongoClient.connect(env.mongoUriAtlas, opt);
  } catch (err) {
    console.error("mongoAsync: CATCH: err.stack... ", err.stack);
    return null;

export default mongoAsync;
Enter fullscreen mode Exit fullscreen mode


We import the npm library, which is the Mongo Driver software that allows us to establish a connection to Mongo

We import our database credentials from the git-ignored ".env" file.

We set our options.
The first two options removing warning flags.
I set the connection timeout a little higher to facilite the pushing of multi-megabyte catalogs and corpora (the plural of corpus) of data.

This wrapper func returns the Mongo client object, which gives your code full power.

The responsibility is on the client code to close the connection.
(I'll show the idiom for that later in the series)

"Atlas" is the name of the MongoDb company's DBaaS (Database as a Service) offering.

That's about it. It's really just a simple wrapper.

What's Next

If you have any questions let me know.

Next I'll show you a couple example of using this wrapper around the Mongo Driver; so you can write fast—sometimes single-line—database queries.

Discussion (0)