Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in
Toggle navigation
E
exam_11_back
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
zarina
exam_11_back
Commits
cbf239e9
Commit
cbf239e9
authored
Jul 22, 2020
by
Алексей Анпилогов
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
#2
, добавила модель юзера
parent
da051612
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
60 additions
and
0 deletions
+60
-0
User.js
models/User.js
+60
-0
No files found.
models/User.js
View file @
cbf239e9
const
mongoose
=
require
(
"mongoose"
);
const
bcrypt
=
require
(
"bcrypt"
);
const
{
nanoid
}
=
require
(
"nanoid"
);
const
Schema
=
mongoose
.
Schema
;
const
SALT_WORK_FACTOR
=
10
;
const
UserSchema
=
new
Schema
({
username
:
{
type
:
String
,
required
:
true
,
unique
:
true
,
validate
:
{
validator
:
async
function
(
value
)
{
if
(
!
this
.
isModified
(
"username"
))
return
;
const
user
=
await
User
.
findOne
({
username
:
value
});
if
(
user
)
return
false
;
},
message
:
props
=>
`Username
${
props
.
value
}
is already exists`
}
},
password
:
{
type
:
String
,
required
:
true
},
displayName
:
{
type
:
String
,
required
:
true
},
phone
:
{
type
:
String
,
required
:
true
},
token
:
String
});
UserSchema
.
pre
(
"save"
,
async
function
(
next
)
{
if
(
!
this
.
isModified
(
"password"
))
next
();
const
salt
=
await
bcrypt
.
genSalt
(
SALT_WORK_FACTOR
);
this
.
password
=
await
bcrypt
.
hash
(
this
.
password
,
salt
);
next
();
});
UserSchema
.
set
(
"toJSON"
,
{
transform
:
(
doc
,
ret
)
=>
{
delete
ret
.
password
;
return
ret
;
}
});
UserSchema
.
methods
.
checkPassword
=
function
(
password
)
{
return
bcrypt
.
compare
(
password
,
this
.
password
);
};
UserSchema
.
methods
.
generateToken
=
function
()
{
this
.
token
=
nanoid
();
};
const
User
=
mongoose
.
model
(
"User"
,
UserSchema
);
module
.
exports
=
User
;
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment