@@ -3,7 +3,7 @@ import mongoose from 'mongoose';
33import bcrypt from 'bcrypt' ;
44import isEmail from 'validator/lib/isEmail' ;
55
6- const UserSchema = new mongoose . Schema ( {
6+ const userSchema = new mongoose . Schema ( {
77 username : {
88 type : String ,
99 unique : true ,
@@ -24,12 +24,9 @@ const UserSchema = new mongoose.Schema({
2424 role : {
2525 type : String ,
2626 } ,
27- messages : [
28- { type : mongoose . Schema . Types . ObjectId , ref : 'Message' } ,
29- ] ,
3027} ) ;
3128
32- UserSchema . statics . findByLogin = async function ( login ) {
29+ userSchema . statics . findByLogin = async function ( login ) {
3330 let user = await this . findOne ( {
3431 username : login ,
3532 } ) ;
@@ -41,17 +38,23 @@ UserSchema.statics.findByLogin = async function(login) {
4138 return user ;
4239} ;
4340
44- UserSchema . pre ( 'save' , async function ( ) {
41+ userSchema . pre ( 'remove' , function ( next ) {
42+ this . model ( 'Message' ) . deleteMany ( { userId : this . _id } , next ) ;
43+ } ) ;
44+
45+ userSchema . pre ( 'save' , async function ( ) {
4546 this . password = await this . generatePasswordHash ( ) ;
4647} ) ;
4748
48- UserSchema . methods . generatePasswordHash = async function ( ) {
49+ userSchema . methods . generatePasswordHash = async function ( ) {
4950 const saltRounds = 10 ;
5051 return await bcrypt . hash ( this . password , saltRounds ) ;
5152} ;
5253
53- UserSchema . methods . validatePassword = async function ( password ) {
54+ userSchema . methods . validatePassword = async function ( password ) {
5455 return await bcrypt . compare ( password , this . password ) ;
5556} ;
5657
57- export default mongoose . model ( 'User' , UserSchema ) ;
58+ const User = mongoose . model ( 'User' , userSchema ) ;
59+
60+ export default User ;
0 commit comments