约束在使用(猫鼬)的模式中无法正常工作

时间:2021-05-25 12:09:01

标签: javascript node.js mongodb mongoose

我有以下架构,其中用户名应至少为 3 个字符。但是当我注册的用户名少于 3 个字符时,它会被注册。唯一约束正常工作,但不是最小最大值。这里有什么问题?

用户架构

const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
    username:{
        type: String,
        required: true,
        unique: true,
        min: 3
    },
    email:{
        type: String,
        required: true,
        max: 50,
        unique: true
    },
    password:{
        type: String,
        required: true,
        min: 8
    },
},
{timestamps: true}
)

module.exports = mongoose.model('user', UserSchema)

用户注册函数

const UserSchema = require("../models/User")
const bcrypt = require('bcrypt')

exports.signup = async (req,res) => {
    try {
        const {username, email, password} = req.body
        const salt = await bcrypt.genSalt(10)
        const hashedPassword = await bcrypt.hash(password, salt)
        const user = new UserSchema({
          username,
          email,
          password: hashedPassword,
          salt
        })
        await user.save()
        res.send(user)
    } catch (error) {
        console.log(error.message);
        res.status(500).send("Server error")
    }
}

0 个答案:

没有答案
相关问题