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
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 where clause. 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
1: Create a new User
Here is the request from the API simulator called POSTMAN.
2: Get user information
3: Get specific user information
4: Update user information
5: Delete user information
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.
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
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?
good !! Thanks…;-)