-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.js
More file actions
41 lines (37 loc) · 1.2 KB
/
Copy pathUser.js
File metadata and controls
41 lines (37 loc) · 1.2 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
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
// Define the structure of a User in the database
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true // User must have a name
},
email: {
type: String,
required: true, // User must have an email
unique: true // No two users can have the same email
},
password: {
type: String,
required: true, // User must have a password
select: false // Don't return password when fetching users
}
}, {
timestamps: true // Automatically add createdAt and updatedAt
});
// IMPORTANT: Hash (encrypt) password before saving to database
userSchema.pre('save', async function() {
// Only hash if password is new or modified
if (!this.isModified('password')) {
return;
}
// Encrypt the password
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});
// Method to check if entered password matches stored password
userSchema.methods.matchPassword = async function(enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
// Export the User model
module.exports = mongoose.model('User', userSchema);