UNPKG

feature-hub

Version:

Feature-based CLI tool to install backend features easily like auth, cron-job, file-upload, etc.

67 lines (61 loc) 1.61 kB
import mongoose from "mongoose"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; const usershema = new mongoose.Schema( { name: { type: String, required: [true, "Please enter a name"], }, email: { type: String, required: [true, "Please enter an email"], unique: [true, "Email should be unique"], }, password: { type: String, required: [true, "Please enter a password"], }, }, { timestamps: true } ); usershema.pre("save", async function (next) { if (!this.isModified("password")) { next(); } const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); }); usershema.statics.findByEmail = async function (email) { const user = await this.findOne({ email }); return user; }; usershema.statics.findById = async function (id) { try { const user = await this.findOne({ _id: id }); return user; } catch (error) { console.log(error.message); throw new Error(error.message); } }; usershema.methods.matchPassword = async function (password) { const isMatch = await bcrypt.compare(password, this.password); return isMatch; }; usershema.methods.getSignedJwtToken = function () { try { const payload = { id: this._id, email: this.email, }; const token = jwt.sign(payload, process.env.JWT_SECRET || "secret", { expiresIn: process.env.JWT_EXPIRE || "3d", }); return token; } catch (error) { console.log(error.message); } }; const userModel = mongoose.model("User", usershema); export default userModel;