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

Intro

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,
};


/*
@func
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

Notes

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

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

3.
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.

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

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

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

7.
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.

Top comments (0)