mongoose验证

mongoose验证

  • 在创建集合规则时, 可以设置当前字段的验证规则, 验证失败则输入插入失败
    1. required: true 必传字段
    2. minlength: 3 字符串最小长度
    3. maxlength: 20 字符串最大长度
    4. trim: true 去除字符串两边的空格
    5. min: 2 数值最小为2
    6. max: 100 数值最大为100
    7. emun: [‘html’, ‘js’, ‘node.js’]
    8. validate: 自定义验证器
    9. default: 默认值
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.log(err, '数据库连接失败'))

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, '请传入文章标题'], // 必传字段
    minlength: [2, '文章长度不能小于2'],
    maxlength: [5, '文章长度不能大于5'],
    trim: true // 去除字符串两边空格
  },
  age: {
    type: Number,
    min: 18,
    max: 100
  },
  publishDate: {
    type: Date,
    // 默认值
    default: Date.now
  },
  category: {
    type: String,
    // 枚举 列举出当前字段可以拥有的值
    enum: {
      values: ['html', 'css', 'js', 'node.js'],
      message: '分类名称要在一定的范围内才行'
    }
  },
  author: {
    type: String,
    validate: {
      validator: (v) => {
        // 返回一个布尔值
        // true 验证成功
        // false 验证失败
        // v 要验证的值
        return v && v.length > 4
      },
      // 自定义错误信息
      message: '传入的值不符合验证规则'
    }
  }
})

const Post = mongoose.model('Post', postSchema)

Post.create({title: 'aaa', age: 20, category: 'java', author: 'ss'})
  .then(result => console.log(result))
  .catch(err => {
    // 获取错误信息对象
    const error = err.errors

    // 循环错误信息对象
    for (var attr in error) {
      // 将错误信息打印到控制台中
      console.log(error[attr]['message'])
    }
  })

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值