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.