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
Optimizing Database Performance with Enteros: Leveraging Cloud FinOps and Observability for the Financial Sector
- 23 December 2024
- Database Performance Management
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…
Enteros: Enhancing Database Security Cost Management with RevOps and AIOps for the Insurance Sector
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…
Enteros: Revolutionizing Database Performance with AIOps, RevOps, and DevOps for the Insurance Sector
- 20 December 2024
- Database Performance Management
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…
Enteros: Transforming Database Software with Cloud FinOps for the Technology Sector
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…