example: route, controller, model

This commit is contained in:
Ben Elferink
2020-12-22 02:11:43 +02:00
parent d389451be2
commit fedda7b932
4 changed files with 50 additions and 1 deletions

View File

@@ -0,0 +1,18 @@
import Example from './../models/model.js';
const getExamples = (request, response) => {
// what is .find() ??? ---> https://mongoosejs.com/docs/queries.html
Example.find((error, allExamples) => {
if (error) {
console.log(`${error}`);
return response.status(404).json(error); // 404 not found + catched error -> send to client
}
// more about response status codes ---> https://restapitutorial.com/httpstatuscodes.html
console.log('✅ -FOUND- :', allExamples);
return response.status(200).json(allExamples); // 200 ok + array of couments -> send to client
});
};
export default getExamples;

View File

@@ -2,6 +2,9 @@ import mongoose from 'mongoose';
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
// import IMPORTED_ROUTES from './routes/route.js';
// un-comment this ^ ^ ^ to use imported route(s)
// doing this will link this following files: index.js -> route.js -> controller.js -> model.js
// initialize app
const app = express();
@@ -23,8 +26,9 @@ mongoose.connection.on('error', (err) => console.log(`❌ MongoDB: ${err}`));
// middlewares
app.use(express.json()); // body parser
app.use(cors()); // enables requests
app.use(cors()); // enables http requests
// routes
app.get('/', (req, res) => res.send('Hello World - Express.js'));
// app.use('/', IMPORTED_ROUTES);
// un-comment this ^ ^ ^ to use imported route(s)

14
server/models/model.js Normal file
View File

@@ -0,0 +1,14 @@
import mongoose from 'mongoose';
const instance = new mongoose.Schema({
/*
name = property of document object
String = type of value ---> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
*/
name: String,
});
// document = model name ---> https://mongoosejs.com/docs/guide.html
const document = 'example';
export default mongoose.model(document, instance);

13
server/routes/route.js Normal file
View File

@@ -0,0 +1,13 @@
import express from 'express';
import getExamples from './../controllers/controller.js'; // import request & response function
const router = express.Router(); // initialize router
/*
1st param = extended path location
2nd param = request & response function
current link: http://localhost:8080/examples
*/
router.get('/examples', getExamples);
export default router;