본문 바로가기

express

How do I do object CRUD?

How do CRUD with models with express.js? I wanted to know the process

My project's structure

MyProject
 - server.js
 - model
  - User.js
 - routes
  - users.js
 - controllers
  - users.js

server.js

This get all of the http request and connect with others. now this will send data to routes/user.js

// Bring express framework
const express = require('express'); 

// Route file
const users = require('./routes/users');    [ 1 ]

// User express from here
const app = express();

// Mount routers
// if client requests to 'prefixed_url',server goes to second parameter which is users route.
app.use('prefixed_url', users);   [ 2 ]

// localhost:5000
const PORT = process.env.PORT || 5000;

app.listen(
  PORT,
  console.log(`Server running now`);
);

[ 1 ] const users = require('./routes/users');

: Bring routes middleware

 

[ 2 ] app.use('prefixed_url', users); / app.use('url', middleware_name);

: Connects to middleware which begins same name with 'prefixed_url'.

 

User model

First we need User model which is structure of user. User model Define what we need when create user objects.

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please add a name']
  },
  email: {
    type: String,
    required: [trye, 'Please add an email'],
    unique: true,
    match: [
      /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
      'Please add a valid email'
    ]
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('User', UserSchema);

 

Using route and contoller

We can put all of the things to 'server.js'. but that is hard to maintain the code. so we divide into several middleware. So now we use routes middleware and controller middleware.

- 'Route' middleware connects to methods that gets request and output resopnse.

- 'Contoller' middleware has methods for each HTTP Request

Routes/users.js

const express = require('express');
const { 
  getUsers,
  getUser,
  createUser,
  updateUser,
  deleteUser
} = require('../controllers/users');

const User = require('../models/User');

// express offer Router library
const router = express.Router();

router
  .route('/')  // react with this url '/'
  .get(getUsers)  // If GET request is comes, send datas to getUser method.
  .post(createUser);  // If POST request is come, send datas to createUser method.
 
router
  .route('/:id')  // react with this url '/:id'
  .get(getUser)  // GET req
  .put(updateUser)  // PUT req
  .delete(deleteUser);  // DELETE req
  
module.exports = router;

Controllers/users.js

const User = require('../models/User'); // bring user model to create user.

// we need to exports methods to use in route !
exports.getUsers = (req, res) => {
  res.status(200).json({ success: true, msg: 'show all users'});
};

// we need to exports methods to use in route !
exports.createUsers = async (req, res, next) => {
  const user = await User.create(req.body);
  
  res.status(201).json({
    success: true,
    data: user
  });
};

// exports.updateUser;
// exports.deleteUser;

 

Done. !

 

now we can

create a user object :"request POST http://localhost:5000/prefixed_url"

search all user : "request GET http://localhost:5000/prefixed_url"

update a user: "request PUT http://localhost:5000/prefixed_url/:id"

delete a user: "request DELETE http://localhost:5000/prefixed_url/:id"

'express' 카테고리의 다른 글

Error Handling using Promise.  (0) 2020.05.16
How does HTTP request looks like  (0) 2020.05.15
UdemyAPI_Define model schema  (0) 2020.05.13
"Udemy" API by myself  (0) 2020.05.13
Udemy course spec/APIs  (0) 2020.05.13