Rest-API-Express-MongoDB
Contingut
Referències
Codi del github:
Seguim el tutorial
Seguim el tutorial sense problemes. La base de dades MongoDB és local (no en el núvol com proposa el tutorial)
$ mkdir restapi_mongodb $ npm init
We need to install a few dependencies now.
npm i express mongoose nodemon dotenv
$ joe index.js const express = require('express'); const mongoose = require('mongoose'); const app = express(); app.use(express.json()); app.listen(3000, () => { console.log(`Server Started at ${3000}`) }) En el package.json: <pre> "scripts": { "start": "nodemon index.js" },
$ npm start > restapi_mongodb@1.0.0 start > nodemon index.js [nodemon] 2.0.16 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node index.js` Server Started at 300
Ara bé la part de crear una base de dades MongoDB. Però en aquest tutorial la creen en el núvol, i nosaltres la volem crear en local.
fitxer .env:
DATABASE_URL = mongodb://localhost:27017/testDatabase
En comptes de postman faig servir curl. Per exemple:
$ curl -i -H "Accept: application/json" -X POST -H "Content-Type: application/json" -d '{ "aaa":"bbb" }' localhost:3000/api/post HTTP/1.1 200 OK X-Powered-By: Express Content-Type: text/html; charset=utf-8 Content-Length: 8 ETag: W/"8-OAZPOApCcxyxOI7T5dJOAUUOqFM" Date: Fri, 06 May 2022 12:43:53 GMT Connection: keep-alive Keep-Alive: timeout=5 $ curl -i -H "Accept: application/json" -X GET -H "Content-Type: application/json" localhost:3000/api/getOne/1000 HTTP/1.1 200 OK X-Powered-By: Express Content-Type: text/html; charset=utf-8 Content-Length: 4 ETag: W/"4-48u6iIP+dGxuNXg8lAS0vAx+6es" Date: Fri, 06 May 2022 12:46:03 GMT Connection: keep-alive Keep-Alive: timeout=5 1000
Un cop la API ja fa la gravació a la bd, anem a provar-ho:
$ curl -i -H "Accept: application/json" -X POST -H "Content-Type: application/json" -d '{ "name":"Joan", "age":"52" }' localhost:3000/api/post HTTP/1.1 200 OK ...
Anem a mirar la bd (repàs de MongoDB):
$ mongo > show dbs ... testDatabase 0.000GB
recordar que per defecte estem connectats a la bd test:
> db test > use testDatabase switched to db testDatabase > show collections datas > db.datas.find() { "_id" : ObjectId("62751a7b26c8db2a5ce59c10"), "name" : "Joan", "age" : 52, "__v" : 0 }
$ curl -i -H "Accept: application/json" -X GET -H "Content-Type: application/json" localhost:3000/api/getAll HTTP/1.1 200 OK ... [{"_id":"62751a7b26c8db2a5ce59c10","name":"Joan","age":52,"__v":0}]
$ curl -i -H "Accept: application/json" -X GET -H "Content-Type: application/json" localhost:3000/api/getOne/62751a7b26c8db2a5ce59c10 HTTP/1.1 200 OK ... {"_id":"62751a7b26c8db2a5ce59c10","name":"Joan","age":52,"__v":0}
$ curl -i -H "Accept: application/json" -X PATCH -H "Content-Type: application/json" -d '{ "name":"Joan", "age":"25" }' localhost:3000/api/update/62751a7b26c8db2a5ce59c10 HTTP/1.1 200 OK ... {"_id":"62751a7b26c8db2a5ce59c10","name":"Joan","age":25,"__v":0}
comprovem que s'ha actualitzat l'edat:
$ curl -i -H "Accept: application/json" -X GET -H "Content-Type: application/json" localhost:3000/api/getOne/62751a7b26c8db2a5ce59c10 HTTP/1.1 200 OK ... {"_id":"62751a7b26c8db2a5ce59c10","name":"Joan","age":25,"__v":0}
I ara esborrem:
$ curl -i -H "Accept: application/json" -X DELETE -H "Content-Type: application/json" localhost:3000/api/delete/62751a7b26c8db2a5ce59c10 HTTP/1.1 200 OK ...
comprovació (només teníem una dada i l'hem eliminat):
$ curl -i -H "Accept: application/json" -X GET -H "Content-Type: application/json" localhost:3000/api/getAll HTTP/1.1 200 OK ... []
Si després de fer les proves vull eliminar el contingut de la col·lecció:
> db.datas.drop()
El script routes.js queda de la següent manera:
const express = require('express'); const router = express.Router() const Model = require('../models/model'); //Post Method router.post('/post', async (req, res) => { const data = new Model({ name: req.body.name, age: req.body.age }) try { const dataToSave = await data.save(); res.status(200).json(dataToSave) } catch (error) { res.status(400).json({message: error.message}) } }) //Get all Method router.get('/getAll', async (req, res) => { try{ const data = await Model.find(); res.json(data) } catch(error){ res.status(500).json({message: error.message}) } }) //Get by ID Method router.get('/getOne/:id', async (req, res) => { try{ const data = await Model.findById(req.params.id); res.json(data) } catch(error){ res.status(500).json({message: error.message}) } }) //Update by ID Method router.patch('/update/:id', async (req, res) => { try { const id = req.params.id; const updatedData = req.body; const options = { new: true }; const result = await Model.findByIdAndUpdate( id, updatedData, options ) res.send(result) } catch (error) { res.status(400).json({ message: error.message }) } }) //Delete by ID Method router.delete('/delete/:id', async (req, res) => { try { const id = req.params.id; const data = await Model.findByIdAndDelete(id) res.send(`Document with ${data.name} has been deleted..`) } catch (error) { res.status(400).json({ message: error.message }) } }) module.exports = router;
creat per Joan Quintana Compte, maig 2022