NodeJs with MongoDB tutorial using mongoose for beginner

This is very simple tutorial for beginner who’s planning to learn NodeJs with MongoDb. This tutorial cover all basic functionality to handle communication between nodejs and MongoDB.

There is a very useful node module available on NPM repository to handle CURD operation called Mongoose, Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily. So here i am going to use this node module to connect mongoDB in nodejs. And show you the basic operation like Save, Update, Fetch and Delete records from mongoDB.

I assumed that you have already installed NodeJs and MongoDB, If not please refer these tutorial to installing them in your linux system.
1. How to install nodejs in ubuntu.
2. How to install mongoDB in ubuntu




First of all create your package.json file in your project directory.

package.json

{
  "name": "NodeJs-mongodb",
  "version": "0.0.1",
  "description": "Simple Nodejs with mongodb tutorial",
  "dependencies": {
    "express": "^4.13.3",
    "mongodb": "^2.1.2",
    "mongoose": "^4.3.4"
  }
}

After that go to your project directory and run command to install all the dependencies from package.json file.

npm install

Create your node server file app.js, Here i am using expressjs a cool nodejs framework. And add required module (express, mongoos) which you have recently installed.

var express    = require("express");
var mongoose = require('mongoose');
var app = express();
var port = Number(process.env.PORT || 5000);
app.get('/',function(req, res){
   res.send("Welcome");
});
 
console.log("Listening on "+port+", Web URL: http://localhost:"+port);
app.listen(port);

Goto command line and test all is working fine or not to ran below command

node app.js

nodejs-mongo-1

hit http://localhost:5000 url on browser as well.
nodejs-mongo-2

This means your nodeJs, ExpressJs with MongoDB environment ready to proceed.



Connect with mongoDb test database.

mongoose.connect('mongodb://localhost/test');

Call Scheme object to design schema for your first db model.

var Schema = mongoose.Schema;

In this example i have created a sample schema for my post model where all post will be store.

// create a post schema with data type
var postSchema = new Schema({
  title: String,
  description: String,
  status: Boolean,
  created: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now }
});

Now Schema has been designed time to create your first model.

// create post model using postSchema
var Post = mongoose.model('Post', postSchema);

Model has been ready to perform real action like Save, Update and Delete

Save Operation

Adding data in Post model

// Insert data in your post table 
var newPost = new Post({
     title: 'Title-1',
     description: 'Description-1',
     status: '1' 
});
 
Post.create(newPost, function (err, small) {
  if (err) return handleError(err);
   console.log("Post saved successfully");
});

OR you can also try this method to adding data in your Post model.

// Insert data in your Post model 
var newPost = new Post({
     title: 'Title-1',
     description: 'Description-1',
     status: '1' 
});
 
newPost.save(function(err) {
  if (err) throw err;
  console.log("Post saved successfully");
});

Use this command to test newPost has been saved in mondoDb or not.
Goto terminal(Ctrl+Alt+t) and use mongodb CLI command to access database attribute.

mongo
show dbs
db.posts.find()

nodejs-mongo-3

After that if test success, Here i am going to show you some fetching method to get stored data from Post model.

Fetch Operation

Fetch all post from Post model

If you pass the blank argument in find method it’ll return all post from the Post model.

Post.find({}, function(err, result) {
  if (err) throw err;
  console.log(result);
});

Fetch specific post

This is conditional, fetch post who’s title match with the given parameter.

Post.find({title:'Title-1'}, function(err, result) {
  if (err) throw err;
  console.log(result);
});

Fetch a post by id

Post.findById(1, function(err, result) {
  if (err) throw err;
  // show the one post which id is 1
  console.log(result);
});

Create custom query to fetch data from Post model

Get one month ago post

 
var monthAgo = new Date();
monthAgo.setMonth(monthAgo.getMonth() - 1);
 
Post.find({ status: true }).where('created').gt(monthAgo).exec(function(err, result) {
  if (err) throw err;
  // show the posts in the past month
  console.log(result);
});



Update Operation

Now next task to update stored data in Post model here are the some methods.

find the post by column and update

Post.findOneAndUpdate({ title: 'Title-1' }, { title: 'Update Title-1' }, function(err, result) {
  if (err) throw err;
  // return updated post
  console.log(result);
});

find the post by id and update title

Post.findByIdAndUpdate(1, { title: 'Update Title-1' }, function(err, result) {
  if (err) throw err;
  // return updated post
  console.log(result);
});

You can also use first get post details then update.

// First get post by id
Post.findById(1, function(err, post) {
  if (err) throw err;
 
  // change the post description
  post.description = 'Update description';
 
  // save the post
  post.save(function(err) {
    if (err) throw err;
    console.log('Post successfully updated!');
  });
});

Delete Operation

Find the post by title and delete

Post.find({ title: 'Title-1' }, function(err, post) {
  if (err) throw err;
 
  // delete 
  post.remove(function(err) {
    if (err) throw err;
 
    console.log('Post successfully deleted!');
  });
});

Find the post by id and delete

Post.findByIdAndRemove(1, function(err) {
  if (err) throw err;
  // deleted the post which id is 1
  console.log('Post deleted!');
});

Find the post by column and delete

Post.findOneAndRemove({ title: 'Title-1' }, function(err) {
  if (err) throw err;
  // deleted the post which title is 'Title-1' 
  console.log('Post successfully deleted!');
});

Hope this simple NodeJs with MongoDB tutorial using mongoose for beginner will help you understand basic nodeJs and mongoDb CURD operation.

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.