Tuesday, February 28, 2017

#1.4 Node.js Basics - user model

Create a model for user, together with some functions to interact with the database:

1. Create /model/user.js as below:

const mongoose = require('mongoose');
const bcrypt   = require('bcryptjs');
const config   = require('../config/database');

// User Schema
const userSchema = mongoose.Schema({
    name:     { type: String },
    email:    { type: String, required: true },
    username: { type: String, required: true },
    password: { type: String, required: true }
});

const user = module.exports = mongoose.model('User', userSchema);

module.exports.getUserById = function (id, callback) {
    user.findById(id, callback)
}

module.exports.getUserByUsername = function (username, callback) {
    const query = { username: username };
    user.findOne(query, callback);
}

module.exports.addUser= function (newUser, callback) {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
            if(err) throw err;
            newUser.password = hash;
            newUser.save(callback);
        })
    })
}

Described above is the DB schema (userSchema), two functions to query user data from DB and one to add user data to DB.




2. Implement the /users/register router in /routes/users.js (changes are in bold):

const express  = require('express');
const router   = express.Router();

const passport = require('passport');
const jwt      = require('jsonwebtoken');
const User     = require('../models/user');


router.post('/register', (req, res) => {
    let newUser = new User({
        name: req.body.name,
        email: req.body.email,
        username: req.body.username,
        password: req.body.password
    });

    User.addUser(newUser, (err, user) => {
        if(err){
            res.json({success: false, msg: 'Failed to register user' });
        } else {
            res.json({success: true, msg: 'User registered' });
        }
    });
})

router.post('/authenticate', (req, res) => {
    res.send('AUTHENTICATE');
})

router.get('/profile', (req, res) => {
    res.send('PROFILE');
})

module.exports = router;

Basically a new object 'newUser' is created with name, email, username and password; Then the function 'addUser' is called in order to save user data into the database.


3. Test the service using Postman (Chrome extension):



Method: Post;
URL: localhost:3000/users/register
Headers -> Content-Type: application/json
Body: raw ->
{
"name": "John Doe",
"email": "john@gmail.com",
"username": "john",
"password": "1234"
}


References:
https://youtu.be/1ZeDy2QI3OE?list=PLillGF-RfqbZMNtaOXJQiDebNXjVapWPZ

1 comment: