-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUsers.js
More file actions
48 lines (39 loc) · 1.27 KB
/
Users.js
File metadata and controls
48 lines (39 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
require('dotenv').config();
mongoose.Promise = global.Promise;
//mongoose.connect(process.env.DB, { useNewUrlParser: true });
console.log(process.env.DB)
try {
mongoose.connect( process.env.DB, {useNewUrlParser: true, useUnifiedTopology: true}, () =>
console.log("connected"));
}catch (error) {
console.log("could not connect");
}
mongoose.set('useCreateIndex', true);
//user schema
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
});
UserSchema.pre('save', function(next) {
var user = this;
//hash the password
if (!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
//change the password
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function (password, callback) {
var user = this;
bcrypt.compare(password, user.password, function(err, isMatch) {
callback(isMatch);
})
}
//return the model to server
module.exports = mongoose.model('users', UserSchema);