Skip to content

Setting Up Node.js with MongoDB on Ubuntu

Advertisement

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

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top