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.
Step 1 – Prerequsities
We assume you already have Node.js and MongoDB installed on your system. If not installed follow our below tutorial first to complete the required installation.
Step 2 – Install mongoose Module
Mongoose provides a straightforward schema-based solution to modeling your application data and includes built-in typecasting, validation and many more.
npm install mongoose
Step 3 – Connect Nodejs with MongoDB
Create a test_server.js file and add below content to the file. 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 lets execute the test_server.js using node. If you get message “Database connected successfully”, It means your node.js app is successfully connecting database.
node test_server.js Database connected successfully