| // 创建用户集合 |
| // 引入mongoose第三方模块 |
| const mongoose = require('mongoose'); |
| // 导入bcrypt |
| const bcrypt = require('bcryptjs'); |
| // 引入joi模块 |
| const Joi = require('joi'); |
| // 创建用户集合规则 |
| const userSchema = new mongoose.Schema({ |
| username: { |
| type: String, |
| required: true, |
| minlength: 2, |
| maxlength: 20 |
| }, |
| email: { |
| type: String, |
| // 保证邮箱地址在插入数据库时不重复 |
| unique: true, |
| required: true |
| }, |
| password: { |
| type: String, |
| required: true |
| }, |
| // admin 超级管理员 |
| // normal 普通用户 |
| role: { |
| type: String, |
| required: true |
| }, |
| // 0 启用状态 |
| // 1 禁用状态 |
| state: { |
| type: Number, |
| default: 0 |
| } |
| }); |
| |
| // 创建集合 |
| const User = mongoose.model('User', userSchema); |
| |
| async function createUser() { |
| const salt = await bcrypt.genSalt(10); |
| const pass = await bcrypt.hash('123456', salt); |
| const user = await User.create({ |
| username: 'iteheima', |
| email: 'itheima@itcast.cn', |
| password: pass, |
| role: 'admin', |
| state: 0 |
| }); |
| } |
| |
| //createUser(); |
| |
| // 验证用户信息 |
| const validateUser = user => { |
| // 定义对象的验证规则 |
| const schema = { |
| username: Joi.string().min(2).max(12).required().error(new Error('用户名不符合验证规则')), |
| email: Joi.string().email().required().error(new Error('邮箱格式不符合要求')), |
| password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码格式不符合要求')), |
| role: Joi.string().valid('normal', 'admin').required().error(new Error('角色值非法')), |
| state: Joi.number().valid(0, 1).required().error(new Error('状态值非法')) |
| }; |
| |
| // 实施验证 |
| return Joi.validate(user, schema); |
| } |
| |
| // 将用户集合做为模块成员进行导出 |
| module.exports = { |
| User, |
| validateUser |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!