DEV Community

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

Posted on • Edited 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.

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping

Top comments (0)

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more