CRUD application using Sails JS and MongoDB Part-I
Today we will make a Books app
Libraries/Modules used:
Mongoose
Sails JS
Please make sure you have node js and sails js installed [Installation]
Initialise the sails project using
sails new books-app
Choose empty project in the console(2)
cd books-app
lets now quickly install all the dependencies
npm i mongodb mongoose
Go inside config/models.js uncomment migrate: ‘alter’ and replace alter with safe. Alter will drop the schema everytime we restart the server which we do not want.
migrate: ‘safe’,
Create a new file called mongoose.js inside config folder
touch config/mongoose.js
We will create our db connection using from this file, now paste the following code in mongoose.js
Generate a file called author inside api/models/author.js
sails generate model author
Inside api/models/author.js remove the existing code and paste the following
Lets now create controllers for author, we start with create and we will here create stand-alone actions [Know more on stand-alone actions!]
sails generate action author/create — no-actions2
We used — no-actions2 flag to use the traditional node js functions rather than sails functions with req and res.
Paste the following code inside you api/controller/author/create.js
Go to config/routes.js and add a route for the api we just created, below the default view route
‘/author/create’: {action: ‘author/create’},
Now its time to test our API, go to postman and create a post request at
localhost:1337/author/create
Fill body as raw json
When you click send you should the response like this
Now go to your mongodb tool, I am using compass and check if the data has been stored or not
Since this article is getting long we will create the rest of end-points in the part-II.