首页 > 解决方案 > 为什么我的猫鼬模式没有验证?

问题描述

我正在尝试使用猫鼬模式验证我的数据。但它不起作用,我不知道为什么。

这是我的架构

var mongoose = require("mongoose");

var UserSchema = new mongoose.Schema({
  username: { type: String, min: 3, max: 30, required: true },
  password: { type: String, min: 6, required: true }
});

mongoose.model("User", UserSchema);

这是我打电话给帖子的地方

router.post('/signup', (req, res) => {
    const user = new User({
        username: "Marcel",
        password: "12345"
    })
    user.save().then(function(){
        res.json({
            message: '✅'
        })
    }).catch(function(){
        res.json({
            message: '❌'
        })
    })
})

我给了密码至少 6 个字符,但是对于示例用户,我给了 5 个字符,所以它不应该工作,但它确实有效。有人能帮我吗?

标签: validationvue.jsmongoose

解决方案


您已经使用了用于Number类型的验证器minmax 。

尝试使用minlengthmaxlength代替,它们适用于String类型:

var UserSchema = new mongoose.Schema({
  username: { type: String, minlength: 3, maxlength: 30, required: true },
  password: { type: String, minlength: 6, required: true }
});

我希望这有帮助。


推荐阅读