In this blog, we will learn how to create a Node.js application with Node-Data. Let’s assume that you are building an application for blogs and you want to create REST APIs which can be used by a front-end/mobile application.
-
- Create blogs into database
- Update blogs into database
- Delete blogs from database
- Find and fetch a blog using any existing blog ID from the database
Prerequisites:
- MongoDB is installed and server is running on a default port
- Node 6.9.0 is installed
- IDE (Eg: VS Code)
- REST client (Eg: Postman, Curl) for testing
Installation:
- git clone https://github.com/ratneshsinghparihar/nodedata-demo-sample.git
- cd nodedata-demo-sample/Demo-Sample
- npm install
Code changes
- Add a model blogmodel.ts inside the Models folder.
- Add a repository blogmodelrepository.ts inside the Repositories folder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {field, document} from 'nodedata/mongoose/decorators'; | |
import {Strict} from 'nodedata/mongoose/enums'; | |
@document({ name: 'blogs', strict: Strict.true }) | |
export class BlogModel{ | |
@field({primary: true, autogenerated: true}) | |
_id: any; | |
@field() | |
name: any; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {repository} from "nodedata/core/decorators/repository"; | |
import {BlogModel} from '../models/blogmodel'; | |
@repository({ path: 'blogs', model: BlogModel }) | |
export default class BlogRepository { | |
} |
- Model with @document to create a document inside Blogs collection.
- A repository with the blog name will create all the necessary REST end points.
Testing
- npm start
- Post a JSON {“name”: “testBlog”} to http://localhost:9999/data/blogs
- Hit the api to get data(http://localhost:9999/data/blogs)
- Hit the api with put method http://localhost:9999/data/blogs/{{blogId}} with body {“name”: “testBlog1”}
- Hit the api with delete method http://localhost:9999/data/blogs/{{blogId}}
Conclusion
Now you can see how creating rest apis is super easy with node-data. If you want to know more check out the our github
https://github.com/ratneshsinghparihar/Node-Data
Or visit our main page