Cây thư mục:
. ├── app.js ├── bin │ └── www ├── package.json ├── controllers ├── public │ ├── images │ ├── javascripts │ └── stylesheets │ └── style.css ├── models ├── routes │ ├── index.js │ └── users.js └── views ├── error.pug ├── index.pug └── layout.pug
Tạo model myModel.js:
var validator = require('validator'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ name : { type: String, required: true }, email : { type: String, required: true, unique: true, lowercase: true, validate: value => { if(!validator.isEmail(value)){ throw new Error({error: 'Invalid Email address'}) } } }, password : { type: String, required: true, minlength: 7 }, tokens: [{ token:{ type: String, required: true } }] }); //pre thao tác trước khi lưu object userSchema.pre('save', async function (next){ var user = this; if (user.isModified('password')){ user.password = await bcrypt.hash(user.password, 8); } next(); }); var User = mongoose.model('user', userSchema); module.exports = User;
Tạo controller MyController.js:
var userModel = require('../models/myModel.js'); module.exports = { list: function(req, res){ userModel.find(function(err, users){ if(err){ return res.status(500).json({ message: 'Error getting user. ' }); } return res.json(users); }); }, register: async function(req, res) { try{ var user = new userModel(req.body); await user.save(); var token = await user.generateAuthToken(); res.status(201).send({user, token}); }catch(error){ res.status(400).send(error); } } }
Trong file route users:
var express = require('express'); var myController = require('../controllers/MyController.js'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.post('/register', myController.register); router.get('/list', myController.list); module.exports = router;