This article will help you to Install MongoDB with NodeJs and configure their connectivity using Mongoose node app on Ubuntu and Debian systems. For PHP users use our previous article to configure MongoDB with PHP and Apache2 on Ubuntu servers.
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.
MongoDB Installation:
Node.js Installation:
Install “mongoose” Module
Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in typecasting, validation and many more.
sudo npm install mongoose
Connect Node.js to MongoDB
Create a test.js file and add following content to the file. For the more details about working with Nodejs and MongoDB with mongoose read this tutorial.
//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.js using node. If you get message “Database connected successfully”, It means your node.js app is successfully connecting database.
node test.js Database connected successfully