1
- import mongoose , { Model , Schema , Types } from "mongoose"
1
+ import mongoose , { Model , Schema , Types , UpdateQuery } from "mongoose"
2
2
import { MongoError } from "mongodb"
3
3
import bcrypt from "bcrypt"
4
4
import { isEmail , isStrongPassword , isAlpha } from "validator" ;
@@ -57,9 +57,7 @@ let User = new Schema<IUser, UserDocumentType>({
57
57
58
58
User . pre ( "save" , function ( next ) {
59
59
const user = this ;
60
-
61
- if ( user . isModified ( "password" ) || user . isNew ) {
62
-
60
+ if ( user . isModified ( "password" ) || user . isNew ) {
63
61
bcrypt . genSalt ( SALT_WORK_FACTOR , function ( error , salt ) {
64
62
if ( error ) {
65
63
return next ( error )
@@ -69,7 +67,7 @@ User.pre("save", function (next) {
69
67
if ( error ) {
70
68
return next ( error )
71
69
}
72
-
70
+
73
71
user . password = hash
74
72
next ( )
75
73
} )
@@ -80,6 +78,32 @@ User.pre("save", function (next) {
80
78
}
81
79
} ) ;
82
80
81
+
82
+ User . pre ( "updateOne" , function ( next ) {
83
+ const update : any = { ...this . getUpdate ( ) } ;
84
+ const context = this ;
85
+ if ( update . password ) {
86
+ bcrypt . genSalt ( SALT_WORK_FACTOR , function ( error , salt ) {
87
+ if ( error ) {
88
+ return next ( error )
89
+ } else {
90
+
91
+ bcrypt . hash ( update . password , salt , function ( error , hash ) {
92
+ if ( error ) {
93
+ return next ( error )
94
+ }
95
+
96
+ update . password = hash
97
+ context . setUpdate ( update ) ;
98
+ next ( )
99
+ } )
100
+ }
101
+ } )
102
+ } else {
103
+ next ( ) ;
104
+ }
105
+ } ) ;
106
+
83
107
User . post ( 'save' , function ( error : Error , doc : Document , next ) {
84
108
if ( error && error instanceof MongoError ) {
85
109
if ( error . code === 11000 ) {
0 commit comments