diff --git a/src/db/connect.js b/src/db/connect.js index 0b79b1d..68116d2 100644 --- a/src/db/connect.js +++ b/src/db/connect.js @@ -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; diff --git a/src/models/user-model.js b/src/models/user-model.js index 22122f6..4f2379e 100644 --- a/src/models/user-model.js +++ b/src/models/user-model.js @@ -37,7 +37,44 @@ 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 @@ -45,6 +82,16 @@ const UserSchema = new mongoose.Schema({}); * 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 * @@ -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;