Preamble

The most popular database management system for Node.js at the moment is MongoDB. To work with this platform, you must first install the server MongoDB itself. More details on how to do this are described here. Besides the Mongo server itself, we need a driver to interact with Node.js.
Start working with MongoDB Node.js
When connecting and interacting with databases in MongoDB we can distinguish the following steps:
- Connecting to the server
- Getting a database object on the server
- Getting the collection object in the database
- Interaction with the collection (add, delete, receive, modify data)
So, let’s create a new project. To do this, define a new directory, which will be called mongoapp. Then let’s define a new file package.json in this directory:
{
"name": "mongoapp",
"version": "1.0.0",
"dependencies": {
"express": "^4.16.0",
"body-parser": "^1.18.0",
"mongodb": "^3.1.0"
}
}
In this case, the last dependency is “mongodb”, which represents the driver. All necessary background information on this particular driver can be found at mongodb.github.io/node-mongodb.
Then let’s go to this directory in the command line/terminal and execute the command to add all the necessary packages:
npm install
Connecting to the database
The key class for working with MongoDB is MongoClient class, and all interactions with the data warehouse will go through it. Accordingly, we must first get MongoClient:
const MongoClient = require("mongodb").MongoClient;
The connect() method is used to connect to the mongodb server:
const MongoClient = require("mongodb").MongoClient;
// create a MongoClient object and give it a connection string
const mongoClient = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true });
mongoClient.connect(function(err, client){
if(err){
return console.log(err);
}
// interaction with database
client.close();
});
At first, the MongoClient object is created. To do this, two parameters are passed to its constructor. The first parameter is the server address. As the address protocol is set “mongodb://”. On the local machine, the address is localhost, after which the port number is specified. By default, the port number is 27017.
The second pair is an optional configuration volume. MongoDb is constantly evolving. In this case, the configuration object is used, which has the property useNewUrlParser: true – it indicates to the infrastructure mongodb, that it is necessary to use a new address parcel server.
Then, a connection to the server is made using the connect method. The method accepts as a parameter the callback function which is triggered when the connection is established. This function accepts two parameters: err (an error that occurred during the connection) and client (a link to a client connected to the server).
If a connection error occurs, we can use the value err to get an error.
If there is no error, we can communicate with the server through the client object.
At the end of the database, we have to close the connection using the client.close() method.
Database, collections, and documents
Having received the object of the disabled client, we can access the database on the server. For this purpose, the method:
client.db("name_bd");
As a parameter, the name of the database we want to connect to is passed to the method.
The database in MongoDB has no tables. Instead, all data falls into collections. And within node.js, to interact with the database (add, delete, read data) we need to get the collection object. To do this, we use the db.collection method (“name_collection”), to which the name of the collection is passed.
Unlike tables in relational systems where all data is stored as rows, in MongoDB collections, data are stored as documents. For example, let us add one document to the database. For this purpose, define the following file app.js in the project directory:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });
mongoClient.connect(function(err, client){
const db = client.db("usersdb");
const collection = db.collection("users");
let user = {name: "Tom", age: 23};
collection.insertOne(user, function(err, result){
if(err){
return console.log(err);
}
console.log(result.ops);
client.close();
});
});
As a database, “usersdb” is used here. It does not matter that there is no such database on the MongoDB server by default. The server shall automatically create such a database the first time it is accessed.
Once connected, we shall access the “users” collection:
const collection = db.collection("users");
Again, it does not matter that such a collection does not exist by default in the usersdb bd, it will also be created the first time.
Once we receive the collection, we can use its methods. In this case, the insertOne() method is used to add a single document – the user object. This method has two parameters – the object to be added itself and the callback function, which is executed after adding. In this function, two parameters are used: err (an error that may occur during the operation) and result (the result of the operation is the added object).
In the callback function, the added object is inspected using the result.ops property. Moreover, it is no longer just a user object, but an object that is obtained back from the database and contains the identifier set at the time of adding.
Now, let us move on the hard disk to the directory where mongodb is installed, and in this directory, let us move to the folder bin:

Let’s run the mongodb server, which is located in this directory and which is a console program mongod.

Then we run our app.js file. As we can see, apart from the initial properties here, the document has an additional property _id, which is a unique identifier of the document that is assigned by the server when it is added.
NodeJS MongoDB Tutorial
Enteros
About Enteros
IT organizations routinely spend days and weeks troubleshooting production database performance issues across multitudes of critical business systems. Fast and reliable resolution of database performance problems by Enteros enables businesses to generate and save millions of direct revenue, minimize waste of employees’ productivity, reduce the number of licenses, servers, and cloud resources and maximize the productivity of the application, database, and IT operations teams.
The views expressed on this blog are those of the author and do not necessarily reflect the opinions of Enteros Inc. This blog may contain links to the content of third-party sites. By providing such links, Enteros Inc. does not adopt, guarantee, approve, or endorse the information, views, or products available on such sites.
Are you interested in writing for Enteros’ Blog? Please send us a pitch!
RELATED POSTS
🧩The Cost of Slow Decisions: How a Global Retailer Lost $3.2M to Data Lag
- 24 October 2025
- Software Engineering
In business, speed doesn’t just close deals — it protects margins.And in this case, it was the lack of speed that quietly drained millions. The Situation A multinational retailer — operating across 14 markets — noticed something puzzling.Their demand forecasts were 97% accurate, yet profit margins were shrinking quarter after quarter. At first glance, it … Continue reading “🧩The Cost of Slow Decisions: How a Global Retailer Lost $3.2M to Data Lag”
Driving Smarter Growth with Enteros: AI Performance Management and Forecasting Models for Accurate Cost Estimation and Operational Excellence
- 23 October 2025
- Database Performance Management
Introduction In an era defined by rapid digital transformation, organizations across industries face the dual challenge of accelerating growth while maintaining cost efficiency. Traditional IT management and forecasting techniques are no longer sufficient to handle the scale, complexity, and dynamic workloads of modern data ecosystems. Businesses require intelligent systems that can not only manage database … Continue reading “Driving Smarter Growth with Enteros: AI Performance Management and Forecasting Models for Accurate Cost Estimation and Operational Excellence”
Transforming Fashion Operations with Enteros: Database Performance Management Meets Cloud FinOps Efficiency
Introduction The fashion industry is undergoing a digital renaissance — one where data, technology, and artificial intelligence intersect to redefine how brands operate, forecast, and engage customers. With the rapid expansion of online retail, omnichannel experiences, and global supply chains, fashion enterprises face increasing challenges in managing vast amounts of data across diverse systems. In … Continue reading “Transforming Fashion Operations with Enteros: Database Performance Management Meets Cloud FinOps Efficiency”
Optimizing Cloud Formation and Storage Efficiency in Technology with Enteros: AIOps and FinOps in Action
- 22 October 2025
- Database Performance Management
Introduction The technology sector is undergoing a cloud revolution. Every enterprise — from SaaS startups to global tech giants — is shifting workloads to the cloud to gain agility, scalability, and cost efficiency. However, as cloud infrastructures expand, managing and optimizing their performance becomes increasingly complex. Cloud Formation, Storage Buckets, and multi-cloud architectures have unlocked … Continue reading “Optimizing Cloud Formation and Storage Efficiency in Technology with Enteros: AIOps and FinOps in Action”