Skip to main content

Meteor JS REST API

RESTful CRUD Operations in Meteor.js

Published Dec 31, 2015Last updated Jan 19, 2017
RESTful CRUD Operations in Meteor.js

Introduction

Meteor is a popular framework for building real-time web applications. We have already covered a tutorial which explains how to build chat system using Meteor.js. In this tutorial, we will learn how to develop a RESTful API using Meteor which perform CRUD operations.

Creating new project

Create a new meteor project using the following command:
meteor create appName
Choose an application name of your choice. Once Meteor is done creating the project, you will see the directories and files created by Meteor in the folder name. We will not need them as of now, so we will delete all of those files and create whatever we need in the coming section.

Installing iron-router

In order to perform routing in Meteor, we will use this awesome package. Run the following command from your terminal and make sure you are in your project directory.
meteor add iron:router
unixroot machine
This will download and install the package into your project, and how much time it takes may vary depending upon the internet connection.

Developing a RESTful API

Like I mentioned, Meteor is tightly coupled with client-side and server-side technologies, so you can code both of them in same project. But we will use REST server-side because we need HTTP to call our endpoint.
Create a new folder in your project called 'server', and create a new file inside it with any name. I will prefer server.js.
We will perform CRUD operation over the REST API on the user model. Here is the Server skeleton.
if(Meteor.isServer) {
   // When Meteor starts, create new collection in Mongo if not exists.
    Meteor.startup(function () {
        User = new Meteor.Collection('user');
    });

// GET /user - returns every message from MongoDB collection.

Router.route('/users',{where: 'server'})
    .get(function(){
        var response = User.find().fetch();
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    })

  // POST /message - {message as post data}
  // Add new message in MongoDB collection.

    .post(function(){
        var response;
        if(this.request.body.userName === undefined || this.request.body.userPassword === undefined) {
            response = {
                "error" : true,
                "message" : "invalid data"
            };
        } else {
            User.insert({
                UserName : this.request.body.userName,
                UserPassword : this.request.body.userPassword
            });
            response = {
                "error" : false,
                "message" : "User added."
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    });

Router.route('/users/:id',{where: 'server'})

    // GET /message/:id - returns specific records

    .get(function(){
        var response;
        if(this.params.id !== undefined) {
            var data = User.find({_id : this.params.id}).fetch();
            if(data.length > 0) {
                response = data
            } else {
                response = {
                    "error" : true,
                    "message" : "User not found."
                }
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    })

    // PUT /message/:id {message as put data}- update specific records.

    .put(function(){
        var response;
        if(this.params.id !== undefined) {
            var data = User.find({_id : this.params.id}).fetch();
            if(data.length > 0) {
                if(User.update({_id : data[0]._id},{$set : {UserName : this.request.body.userName,UserPassword : this.request.body.userPassword}}) === 1) {
                    response = {
                        "error" : false,
                        "message" : "User information updated."
                    }
                } else {
                    response = {
                        "error" : true,
                        "message" : "User information not updated."
                    }
                }
            } else {
                response = {
                    "error" : true,
                    "message" : "User not found."
                }
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    })

    // DELETE /message/:id delete specific record.

    .delete(function(){
        var response;
        if(this.params.id !== undefined) {
            var data = User.find({_id : this.params.id}).fetch();
            if(data.length >  0) {
                if(User.remove(data[0]._id) === 1) {
                    response = {
                        "error" : false,
                        "message" : "User deleted."
                    }
                } else {
                    response = {
                        "error" : true,
                        "message" : "User not deleted."
                    }
                }
            } else {
                response = {
                    "error" : true,
                    "message" : "User not found."
                }
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    });
  }

Explanation

On the Meteor server's startup, we are creating a new MongoDB collection only if its not created ( Meteor will do the validation that collection is created or not ) .
We are checking whether this route is for the Server or Client using the whereclause. This will determine that this code will not do front-end routing.
Here is how we are doing the CRUD operation on user model.

1 : GET /users

This request means "pull every user from model", so we will run the MongoDB fetch query and pull of them from our database. We will form JSON response of its JSON.stringify() function and set its headers so that the User interface or REST tool can interpret it.

2 : GET /users/:id

In this request, we need to pull the data of a specific user. So to do that we need to following :
  • Find whether the user exists or not.
  • If the user exists, then return the user's data
  • else, return an error message.
In order to find the user, we are using same function .fetch(), but with the user id as our parameter.

3: POST /users - Create new user

In this request, we will create a new user in our model. In order to do that, we are using MongoDB's create() function using our Model name which is User.

4: PUT /users/:id

In this request, we will update the user information. In order to do that, we will do following :
  • Find whether the user exists or not.
  • If the user exists, then update the user's data
  • else, return an error message.
We are using the .fetch() function to do the validation, and MongoDB .update()function to override data in the Mongo model.

5: DELETE /users/:id

In this request, we will delete the user's data. In order to do that we will do following :
  • Find whether the user exists or not.
  • If the user exists, then delete the user's data
  • else, return an error message.
We are using the .fetch() function to do the validation, and MongoDB's `.remove()' function to do the deletion.

Running the code

Go to your project directory and type the following command to run your project.
meteor
unixroot machine

1: Create a new User

Here is the request from the API simulator called POSTMAN.
unixroot machine

2: Get user information

postman api sim

3: Get specific user information

postman api sim

4: Update user information

postman api sim

5: Delete user information

postman api sim

Conclusion

Meteor provides us a very flexible way to develop real time applications using JavaScript. REST API's are one of the widely-used approaches for mobile app development or web app development, and Meteor made it really easy.
Shahid Shaikh
Enjoy this post?
Leave a like and comment for Shahid
3
3
3Replies
manish kakoti
6 months ago
Hi, that’s a pretty good tutorial, but i am facing an error, while inserting data, i am getting null values inserted, i have removed the type check === undefined from your code, how do i fix it
office beacon
a year ago
Nice tutorial . I have a only 1 question that every time i am getting blank body in post request from postman . can you relate with that issue?
Luigi Parisi
a year ago
good !! Thanks…;-)

How to build a range slider component in React from scratch using only div and span

How to build a range slider component in React from scratch using only div and span
In this article, we will build a React range slider component step by step using only <div>. We will enable it with touch support.
What can you do with a piece of about 50 <div’s>?
Build a slider control from scratch. If this sounds interesting, then follow along.
The final output will look like the below animation.
Please do note that I have developed this component as a teaching exercise for my students of [ReactJS — Beyond the Basic ...
READ MORE

Comments

Post a Comment

Popular posts from this blog

Meteor Mongodb Mup Commands

docker exec -it mongodb mongo docker cp mongodb:dump/ce5-meteor . If deployed with mup, you are in luck. You can find the steps here:  https://github.com/xpressabhi/mup-data-backup Here are the steps again: MongoDB Data Backup deployed via mup These commands run well only if meteor deployed with mup tool. Mup creates docker for mongodb hence taking backup becomes easy with these commands. Backup Take backup of running app data from docker then copy to local folder out of docker. docker exec -it mongodb mongodump --archive= /root/m ongodump. gz --gzip docker cp mongodb : /root/m ongodump. gz mongodump_$ (date +%Y-%m-%d_%H-%M-%S). gz Copy backup to server Move data to another server/local machine or a backup location scp /path/to/dumpfile root@ serverip : /path/ to/backup Delete old data from meteor deployment Get into mongo console running in docker then drop current database before getting new data. docker exec -it mongodb mongo appName db. runCommand ( { dropDatabase : 1 } ) ...