Skip to content

mongodb-intro-workshop - Ivan Escribano #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
17 changes: 4 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion src/db/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ const mongoose = require("mongoose");
* useUnifiedTopology: true,
* }
*/
function connect() {}
function connect() {
return mongoose.connect("mongodb://localhost:27017/myApp", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
}

module.exports = connect;
59 changes: 58 additions & 1 deletion src/models/user-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,49 @@ 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: (value) => validator.isEmail(value),
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",
],
},
],
},
{ timestamps: true },
);

/**
* 3. encrypt the password before storing it in the database
Expand All @@ -50,7 +92,22 @@ const UserSchema = new mongoose.Schema({});
*
* The `comparePassword` method should return a `bcrypt.compare` function call
*/
UserSchema.pre("save", async function userPreSaveHook(next) {
if (!this.isModified("password")) return next();

try {
const hash = await bcrypt.hash(this.password, 12);

this.password = hash;

return next();
} catch (error) {
return next(error);
}
});
UserSchema.methods.comparePassword = function (candidate) {
return bcrypt.compare(candidate, this.password);
};
const UserModel = new mongoose.model("user", UserSchema);

module.exports = UserModel;