eCommerce Platform 03 - Database, MongoDB, Postman
Contents
Mongo DB Atlas & Compass Setup
Download Compass
Create Database(Cluster) in mongodb.com
- Security => Database Access => Add new database user
- Network Access => Add IP Address => Allow Access From Anywhere => Confirm
- Databases => Browse Collections => Add my Own Data
- db name: eshop
- collection name: products
- Databases => Connect => Connect using MongoDB Compass => I have MongoDB Compass
- Copy the connection string, and paste in MongoDB Compass App
- modify
<password>
and /test => /eshop
- Databases => Connect => Connect your application (Node.js)
- copy the connection string into Node.js Code
- paste to
.env
with prefixMONGO_URI =
- modify
<passowrd>
and<dbname>
before?
- modify
Connecting to the Database
mongoose: elegant mongodb object modeling for node.js
|
|
Create backend/config/db.js
- async: since
.connect
,.find
or.create
will return a promise - await: since mongoose.connect() returns a promise
- host: cluster0-shard-00-01.qvmrm.mongodb.net
|
|
Connect DB in server.js
|
|
Create Data Models
Create backend/models/userModel.js, productModel.js, orderModel.js
|
|
|
|
|
|
Sample Data for users and products
Create backend/data/users.js
- Use hashSync method to hash the password synchronously
|
|
|
|
When data is entered into MongoDB, it automatically creates an _id
- delete
_id
s in products.js
Data Seeder Script
Create backend/seeder.js
- easily import some sample data
- deleteMany before import data because we don’t want to import anything with stuff already in the database
|
|
In package.json
|
|
In terminal, run
- check data imported in
eshop.products
andeshop.users
collections inMongoDB Compass
|
|
Fetch Products from Database
Create backend/routes/productRoutes.js
- move routes from
server.js
- add
express-async-handler
: Simple middleware for handling exceptions inside of async express routes and passing them to your express error handlers.
|
|
|
|
In server.js
|
|
Postman
Download and create a new collection eshop
- Add Environment Variable:
eShop Env
- VARIABLE:
URL
- INITIAL VALUE:
http://localhost:5000
- env var is in
{{}}
in request
- VARIABLE:
- create folder
Products
- Add
request
:GET /api/products
- GET:
{{URL}}/api/products
- Click Send and get data
- GET:
- Add
Custom Error Handling
We want to send back an error message in JSON format rather than in HTML format when the :id
format is wrong
Create backend/middleware/errorMiddleware.js: functions that has access to the request-response cycle
- 500: server error
|
|
In server.js
|
|
Now fetch products from component,
- will do: use Redux so that have global state to get products and then pass them down
- create
reducer
andaction
- create