UNPKG

hrms-shared

Version:

HRMS shared code: models, middleware, utils

57 lines (51 loc) 1.45 kB
const mongoose = require("mongoose"); const bcrypt = require("bcrypt"); module.exports = (connection) => { const { Schema } = mongoose; const schema = new Schema( { name: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, roleId: { type: mongoose.Schema.Types.ObjectId, ref: "Role", }, companyId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "Company", }, registeredBy: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User", }, }, { timestamps: true, collection: "User", } ); schema.pre("save", async function (next) { if (!this.isModified("password")) return next(); try { const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next(); } catch (error) { next(error); } }); return connection.models.User || connection.model("User", schema); };