< All Docs

How to Connect Node.js Application with MongoDB on CentOS

Create a Microhost account to try this guide with a $50 credit.

Table of Content

This article will help you to connect Node.js application with MongoDB. Also, configure MongoDB drive for nodejs using Mongoose node application on CentOS and Redhat systems.

Prerequsities

We assume that Node.js and MongoDB are already installed on your server. If not installed first follow our guide below to complete the installation.

Install mongoose Module

Mongoose offers a simple schema-based approach for modeling data about the program which includes built-in typecasting, validation and much more.

npm install mongoose

Connect Nodejs with MongoDB

Create a file test server.js, and add content to the file below. For the more details about working with Node.js and MongoDB with mongoose read this tutorial.

</ Sample script of Node.js with MongoDB Connection

// This code requires mongoose node module
var mongoose = require('mongoose');

// Connecting local mongodb database named test
var db = mongoose.connect('mongodb://127.0.0.1:27017/test');

// testing connectivity
mongoose.connection.once('connected', function() {
 console.log("Database connected successfully")
});

Now we execute the test_server.js using node. If we get message “Database connected successfully”, It means our node.js app is successfully connecting database.

node test_server.js

Output - database connected successfully

We have connected Node.js Application with MongoDB successfully on CentOS.

Thankyou.

Previous How To Configure SFTP Server In Debian
Next How to create an email account in Plesk And set email forwarding
Table of Contents