Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

Creating a User model


We don't have a collection yet to manage the users. We will have three parameters in our


User model: name, email, and password. Let's go ahead and create our User model called


User.js in the models directory:


const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
password: String,
});

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

As you can see, the following are the three attributes for the user: name, email, and


password.


Installing bcryptjs


Now, we cannot save these user's passwords in plain text, so we will need a mechanism to


encrypt them. Fortunately, we already have a package designed to encrypt passwords,
which is bcryptjs. Let's first add this package to our application:


$ npm install bcryptjs --save

When the package is installed, let's add the initialization block in the User.js model:


const mongoose = require('mongoose');
const bcryptjs = require('bcryptjs');

const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
password: String,
});

const User = mongoose.model('User', UserSchema);
module.exports = User;
Free download pdf