showing results for - "mongoose middleware example"
Silas
31 Apr 2018
1const mongoose = require('mongoose')
2const bcrypt = require('bcrypt')
3const todosSchema = require('./model.todos')
4
5const AuthSchema = mongoose.Schema({
6	email: {
7		type: String,
8		unique: true,
9		trim: true,
10		required: true
11	},
12	password: {
13		type: String,
14		trim: true,
15		required: true
16	},
17	createdAt: {
18		type: Date,
19		default: new Date()
20	},
21	updatedAt: {
22		type: Date,
23		default: new Date()
24	}
25})
26
27AuthSchema.pre('save', async function (next) {
28	if (this.isModified('password')) {
29		const salt = await bcrypt.genSalt(10)
30		this.password = await bcrypt.hash(this.password, salt)
31	}
32	next()
33})
34
35AuthSchema.post('save', async function (doc, next) {
36	const checkId = await todosSchema.findById(this._id)
37	if (!checkId) {
38		await todosSchema.create({ userId: mongoose.Types.ObjectId(this._id) })
39	}
40	next()
41})
42
43module.exports = mongoose.model('auth', AuthSchema)