Hello, today we will talk about the potential that jointly have MongoDB And NodeJS. These two Open Source tools are often used in new projects. In today’s article, let’s tell you how to create a project from scratch with these two technologies, but before we see, what is each.
What is MongoDB and NodeJS?
MongoDB is the most popular NoSQL database of the moment. This type of database offers the advantage, among many others, of creating “to measure” records without a defined fixed structure. For example, in a relational database (such as MySQL), you start working with a table “employees” in which only the name and surname data is saved. Years later, it is required to include the “delegation” in the database, and to add such information only to employees who are in a delegation, not central office employees.
Difference between relational database and NoSQL
A relational database would have to create a table of “delegations” and unite employees with a new field leaving with value “null” to employees working in central. With MongoDB, we have it easier, only to employees who are in delegation, you can add the attribute “delegation”, thus avoiding occupying unnecessary space by adding null values. For example:
{Name: "Carlos", Surnames: "Yébenes Dorado", delegation: "Madrid"} {Name: "Antonio", Surname: "Hidalgo Jiménez", delegation: "Sevilla"} {Name: "Elsa", Last Name: "Sánchez Delgado"} {Name: "David", Last Name: "González López"}
In the previous example, the first two would work in delegation, but the last two would work in central. You could add more attributes to them, for example, the “fechaBaja” field only to employees who no longer work in the company. It is not necessary to have a fixed structure with MongoDB.
What is NodeJS?
NodeJS is a new programming language that allows you to run JavaScript code on the server side. So far, JavaScript, was used to perform small operations in the browser, such as events on a button, form validation, etc. But now we can use nodeJS as a web server with just a few lines of code, Replacing Apache Or Nginx. One of the advantages of NodeJS is that being based on JavaScript, the learning curve for a web programmer, is very fast, having notions of JavaScript.
Now that we know what each one is, we will create our first application from scratch.
Creating the Project
In this example we will dispense with the web server and use directly defined actions in JS files. NodeJS and NPM must be installed previously.
1-Creating the folder
First of all, we will have to create an empty folder in the path that we want. This folder will contain the project and we must access it to run the files. For example:
mkdir test_mongodb_nodejs Use test_mongodb_nodejs
2-Generate the file package.json
Inside the folder, we execute:
NPM init
This command, you will ask us through the console, several data to fill, as the version, the author, license, etc. We can generate It with the default options by pressing ENTER in each question, but there is a very important value that we must fill. This value is: “entry point: (Index. js)”. If nothing is indicated, it will set index. JS. This file will be responsible for starting the project.
With this data, we will generate the file package.json, which tells NodeJS, the libraries and details of the project.
3-Install the MongoDB driver for NodeJS
Once the package. json file has been generated, we will have to install the MongoDB driver by executing:
NPM install MongoDB
This command will generate a folder called “Node_modules” with the packages needed to use MongoDB and modify the package. json file to use it.
4-We create our first employee
Once the necessary structure and files have been created, we will be able to execute our project. To do this we must create the file “index. js” with the following content:
MongoDB Driver Const MongoClient = require (' MongoDB '). MongoClient; Connection string Const URI = "CADENA_DE_CONEXION_A_MONGODB"; const connection = new MongoClient (uri, {useNewUrlParser: true}); IF THE CONNECTION IS CORRECT Connection. Connect (err => { WE DEFINE THE TABLE Const employees = connection. db ("miempresa"). collection ("Employees"); INSERTION OF AN EMPLOYEE We define employee data var employee = {Name: "Carlos", Surnames: "Yébenes Dorado"}; We carry out the insertion with insertOne employees. insertOne (employee, function (err, res) { If there is an error, it will return the error if (err) throw err; If It went well, it will show it on the console console.log ("Employee correctly inserted"); }); Connection.close (); });
The previous code, generates our database and our collection (equivalent to a table in a relational database), and inserts the first document (registry) into it. To execute it, we will use:
node index.js
We can verify that it was created by accessing the database:
5-We create several employees
With the command insertOne we have inserted an employee, but we can insert several slightly changing the code with the command insertMany:
MongoDB Driver const MongoClient = require (' MongoDB '). MongoClient; Connection String Const URI = "CADENA_DE_CONEXION_A_MONGODB"; Const CONNECTION = new MongoClient (URI, {useNewUrlParser: true}); IF THE CONNECTION IS CORRECT Connection. Connect (err => { WE DEFINE THE TABLE Const employees = connection. db ("miempresa"). collection ("Employees"); MULTI-EMPLOYEE INSERTION var Employeelist = [ {name: ' Arturo ', Last name: ' López de la Rosa '}, {name: ' Alberto ', Last Name: ' Domínguez Ramírez '}, {name: ' Laura ', Last Name: ' Cano Alumos '}, {name: ' Hector ', Last Name: ' Fernández Lanza '}, {name: ' Fernando ', Last Name: ' Barrutia Rodríguez '}, {name: ' Luis ', Last Name: ' García Bueno '}, {name: ' Carlos ', Last Name: ' Martínez Pisuerga '}, {name: ' Samuel ', Last Name: ' Madrid Ocaña '}, {name: ' Óscar ', Last Name: ' Pérez Reverte '} ]; Employees. insertMany (Employeelist, function (err, res) { If there is an error, it will return the error if (err) throw err; If It went well, it will show it on the console Console. Log ("properly inserted Employees"); }); Connection.close (); });
We can create another file (indexMany. js) and run it with:
Node indexMany. js
After this you will have created the rest of users.
They are just a few examples, but they can serve as a basis for creating new projects. You can see more actions available from MongoDB on the following page: https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne
If you don’t want to miss articles about MongoDB and NodeJS and other open source technologies, subscribe to our newsletter. With just one email per month, you’ll enjoy these items in your inbox.
We hope that it has helped you.
Greetings,
Database Team