Easy steps to build a simple CRUD app with Node, Express and MongoDB.
(Backend)
After understood how to work with Node, I wanted to write an easy and comprehensive guideline for a full Crud using Express and MongoDB.
create the application folder
mkdir todo-app
cd todo-app
create the backend folder
mkdir todo-backend
create the front end react app
npx create-react-app todo-frontend
now you should have a folder structure like so
todo-app
- todo-backend
- todo-frontend
- node_modules
- public
- src
- package.json
- .gitignore
- README.md
Building backend
navigate to the todo-backend
folder cd todo-backend
and run npm init -y
It will create a package.json files and we will also install other packages that we will need to build the express server
npm install express express-validator mongoose
- ExpressJS — is the server framework with Node JS under the hood.
- express-validator— express-validator is a set of express.js that check the validation of the user input.
- mongoose — high level API for interacting with our MongoDB database.
And install the dependency
npm install -D nodemon concurrently
- Nodemon — This tools allows you to edit your server files and see the change propagate in real time without starting the server each time.
- Concurrently — Run multiple commands concurrently, we will use it to run the frond and back in one command.
create the index.js
which will store our server initialization logic and inside let ‘s copy this code:
const express = require('express'); // our express serverconst app = express(); // generate an app objectapp.get('/',(req,res)=> res.send('Api Running')); // sending a get request to test our appconst PORT = process.env.PORT || 5000;
//port that the server is running on => localhost:5000app.listen(PORT, () => {
// listening on port 5000
console.log(`listening on port ${PORT}`) // print this when the server starts
})
Run the server use this command line: nodemon index.js
then open the browser at http://localhost:5000/ and if no surprise we should see our message displayed.