vishwaefor / article-hub

This is a REST API using NodeJS Express + MongoDB
Apache License 2.0
0 stars 37 forks source link

Register user #7

Open vishwaefor opened 5 years ago

vishwaefor commented 5 years ago

Steps

-Step 4

Save user in the db

var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');

const Users = require('../models/users');

router.use(bodyParser.json());

router.post('/', function(req, res, next) {
  let user = req.body;

  new Promise((resolve, reject) => {
    bcrypt.hash(user.password, 10, (err, hash) => {
      if (err) {
        reject(err);
      } else {
        user.password = hash;
        resolve(user);
      }
    });
  })
    .then(user => {
      return Users.create(user);
    })
    .then(user => {
      console.log('user created', user.name, user.email);
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.json({ id: user._id, name: user.name, email: user.email });
    })
    .catch(err => {
      next(err);
    });
});

module.exports = router;