My HP

27th September, 2021 | Tutorials |

Node.js and MongoDB: How to Connect MongoDB With Node

Looking for Node.js hosting? Check out our optimised packages.

Get Node.js Hosting

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant document-oriented database segment and its ease of use, flexibility and wide adoption have made it the most adopted database technology for new projects that do not have an obvious reason to start with an SQL database . For Node.js applications, MongoDB is the perfect tool for prototyping.

In a MongoDB database, your data is stored in the form of JSON objects. In most cases, all the data linked to this object is found in a single document, unlike SQL databases where you have to make joins on different tables in order to assemble a document.

{
  "_id":"5beca8f00000000000000000",
  "name": "John",
  "contacts": {
    "tel":"+123456789",
    "email":"john@email.com"
  },
  "status":"pending"
}

As you can see, the document has several fields, which store values. These values can contain strings, numbers, matrices, sub-document matrices (for example, the field categories ), geographic coordinates, and much more.

Primary keys are assigned by default to fields that contain the _id name. It must have a unique value within the collection. Additionally, it is immutable and may not be of an array type. BSON (binary JSON) is what MongoDB internally uses although it is not necessary to understand BSON when working with MongoDB. It follows that a document in a NoSQL database corresponds to a row in a SQL database. Compared to a table in a relational database, a collection of documents is equivalent to a set of documents.

Node.Js - MongoDB: Connect Your App to the Mongo Database

To use MongoDB, you can install it on your machine or use a docker image for local use. You can also use a Database as a Service cloud solution, such as MongoDB Atlas. Until recently, a MongoDB cluster accepted a limited number of simultaneous connections. In a classic client-server architecture, there is no problem because all that is needed is a permanently open TCP connection for each instance of the server. Transactions can then be processed quickly by the MongoDB server. Except that a Serverless architecture is no longer a predefined number of servers that process all incoming requests but a variety of ephemeral instances that must each create a connection and perform the operation before disappearing.

In June 2020, MongoDB commissioned their Atlas Data Lake service.

Unlike Data Warehouses such as Snowflake or Redshift which require processing before data can be inserted, Atlas Data Lake has been designed to provide document flexibility in modeling the data that the Data Lake can receive.

Node.js-MongoDB: Connecting application with MongoClient

The process to connect the Node.js application with MongoDB using MongoClient is fairly easy. Once Node.js has been correctly installed on our machine, we can use its internal package manager (the NPM - Node Package Manager) to install the MongoJS module that we will need to be able to interact with our Database through a written app for Node.js. Start by adding the Mongodb to your project by entering the command npm install MongoDB in your terminal at the root of your project.

Coding a node server is much easier to do. Here's what the code for an extremely simple web server js node looks like:

const http = require("http");

const server = http.createServer(function(req, res) {

// Upon arrival of a request res.write("Hello World!"); res.end(); })

// Start the server server.listen(3000)

In 5 lines, you have enough to receive customer requests and be able to answer them, at least a Hello World!

In your index.js file (or the file where you start your express server), add the following code before launching your server:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017' const dbName = 'ProjetMongo';

MongoClient.connect(url, function(err, client) { console.log("Connected to MongoDB"); const db = client.db(dbName); client.close(); });

The databaseUrl variable can contain the server host with the port and name of the database we want to connect to. In our case we use the default values: the host is “localhost” and the port is 27017.

By relaunching your Node.js application, you should see in your terminal "Connected to MongoDB" if your connection is well established.

Run Mongo Queries Through Your Node.Js App

With your database now connected, you can create mongoDB operations to create, read, modify or delete a document. With the mongo client, you will operate directly with the commands defined by MongoDB.
Here is an example of creating a document:

onst createStudent = async object => { const collection = db.collection('students'); const student = await collection.insertOne(object); return student } const newStudent = { name:"john", status:"student" } const insertStudent = await createStudent(newStudent) console.log(newStudent)

In this example, the function createStudent will take care of inserting the object that you will pass as a parameter into the Student collection. After defining this function and the new student you wanted to insert, can be called using the createStudent function, passing this student as a parameter. The collections variable is a set of data (array) that our app uses. It is not mandatory but it allows us to emulate a javascript client as it happens in the MongoDB API within our Node.js app.

const insertStudent = await createStudent(newStudent)
console.log(newStudent)

Node.js implements a paradigm based on concurrent events and therefore pretty much everything is a callback. This allows the app not to crash and to run at high performance.

Node.js-MongoDB: Connecting app using Mongoose

The configuration is relatively simple, at the beginning it may be a bit confusing and this depends on how you have your project organized in Node.

As for MongoClient, install mongoose on your project via the command npm install mongoose.

Before launching your server, add the following code:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to Mongoose")
});

By restarting your Node.js server, you should see in your terminal "connected to Mongoose" if your connection is well established. Otherwise, a message containing the error if the connection could not be made.

Running Queries With Mongoose

Unlike MongoClient, Mongoose requires you to define your schemas before manipulating your objects. Let's start by creating the first schema in a file student.js.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const studentSchema = new Schema({
    firstName:  String,
    lastName: String,
    cursus:   String,
    classes: [{ body: String, date: Date }],
    enrolled: { type: Date, default: Date.now }
  });
const Student = mongoose.model('Student', studentSchema)
module.exports = Student

This file will contain the Student module, which is a mongoose schema. We have the properties that one student can contain. Once this schema is defined, you can now use the mongoose schema methods to perform our creation, modification or deletion operations.

const Student = require('./student.js')
// Create a student
const createStudent = async studentData => {
 const student = await Student.create(studentData)
 return student
}
// Pick up a student
const findStudent = async firstName => {
 const student = await Student.findOne({firstName})
 return student
}
// Collect all students
const findStudents = async firstName => {
 const student = await Student.find({})
 return student
}

Here you will find the list of possible queries to manipulate your objects via mongoose.

In most cases, we recommend using Mongoose for your MongoDB nodejs application projects. It will allow you to impose a structure on your data while simplifying the queries.

On the other hand, if you are looking to prototype something or want to practice your MongoDB skills then mongoClient allows you to be as close as possible to the database and to handle mongo's native queries.

Looking for Node.js hosting? Check out our optimised packages.

Get Node.js Hosting

Comments