Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/db/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ const mongoose = require("mongoose");
* useUnifiedTopology: true,
* }
*/
function connect() {}
function connect() {
// TODO: return the call to mongoose.connect
return mongoose.connect("mongodb://localhost:27017/myApp", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
}

module.exports = connect;
55 changes: 54 additions & 1 deletion src/models/user-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,61 @@ const bcrypt = require("bcrypt");
* 2.6 with the "createdAt" and "updatedAt" properties that are created automatically
*/

const UserSchema = new mongoose.Schema({});
const UserSchema = new mongoose.Schema({
firstName: {
type: String,
required: [true, "The first name is required"],
trim: true,
},
lastName: {
type: String,
required: [true, "The last name is required"],
trim: true,
},
email: {
type: String,
required: [true, "The email is required"],
trim: true,
unique: true,
validate: {
validator: validator.isEmail,
message: (props) => `The email ${props.value} is not valid`,
},
},
password: {
type: String,
required: [true, "The password is required"],
minlength: [8, "The password is too short"],
},
speaks: {
type: [String],
enum: [
"english",
"spanish",
"catalan",
"german",
"italian",
"javascript",
],
},
});

/**
* 3. encrypt the password before storing it in the database
*
* Use a salt round of 12
*/

UserSchema.pre("save", async function (next) {
const user = this;

if (user.isModified("password")) {
user.password = await bcrypt.hash(user.password, 12);
}

next();
});

/**
* 4. add a 'comparePassword' method to the 'User' schema
*
Expand All @@ -53,4 +100,10 @@ const UserSchema = new mongoose.Schema({});

const UserModel = new mongoose.model("user", UserSchema);

UserSchema.methods.comparePassword = async function (password) {
const user = this;

return await bcrypt.compare(password, user.password);
};

module.exports = UserModel;