MongoDB基础七:Mongoose 数据校验

2019-06-09  本文已影响0人  joyitsai

一、Mongoose 校验参数

在定义Schema时,可以设置数据的校验参数,这样可以对操作数据库数据时,对其做进一步的规范。主要的校验参数有:

1.1 required示例:
// 定义news_id是必须要传入的数据
const NewsSchema = mongoose.Schema({
    news_id:{
        type:Number,
        // 唯一索引
        unique: true,
        required: true
    },
    title: {
        type:String,
        // 普通索引
        index: true
    },
    author: String
});

const News = mongoose.model('News', NewsSchema, 'news');
module.exports = News;

现在我们在news集合中添加数据时,如果没有传入news_id的字段数据,就会报错:

const news = new News({
    /*此处没有传入news_id数据*/
    title: '新闻1',
    author: 'joyitsai'
})

news.save((err, docs)=>{
    if(err) return console.log(err);
    console.log(docs);
})

运行报错:

{ ValidationError: News validation failed: news_id: Path `news_id` is required.
  .....
}
1.2 maxmin示例:

如果Schema定义时,指定maxmin,那么传入的数据值必须在min和max之间,否则报错:

const NewsSchema = mongoose.Schema({
    news_id:{
        type:Number,
        // 唯一索引
        unique: true,
    },
    title: {
        type:String,
        // 普通索引
        index: true
    },
    author: String,
    words: {
        type: Number,
        min: 200,
        max: 1000
    }
});

const News = mongoose.model('News', NewsSchema, 'news');
module.exports = News;

现在如果添加数据时words为100:

const news = new News({
    news_id: 2,
    title: '新闻2',
    author: 'joyitsai',
    words: 100
})

news.save((err, docs)=>{
    if(err) return console.log(err);
    console.log(docs);
})

就会提示数据不能小于min的值,相反如果数据大于max也会提示相应错误:

{ ValidationError: News validation failed: words: Path `words` (100) is less than minimum allowed value (1000).
  ......
}

其他的几个参数就不一一举例了,请自行验证。

二、自定义校验:

类似于之前set的用法,在定义Schema时可以用validate关键字自定义一个校验器函数,来检测数据是否满足想要的规范,如果通过验证返回true,没有通过则返回false:

const NewsSchema = mongoose.Schema({
    news_id:{
        type:Number,
        // 唯一索引
        unique: true,
    },
    title: {
        type:String,
        // 普通索引
        index: true
    },
    author: String,
    content: {
        type: String,
        /*words的长度要大于8且小于20*/
        validate: function(words){
            return (words.length>=8 && words.length<=20)
        }
    }
});

添加数据时:

const news = new News({
    news_id: 2,
    title: '新闻2',
    author: 'joyitsai',
    words: 'qwert'
})

news.save((err, docs)=>{
    if(err) return console.log(err);
    console.log(docs);
})

提示报错:

{ ValidationError: News validation failed: words: Validator failed for path `words` with value `qwert`
  ......
}

如果添加的words数据长度在8-20之间,就没问题了:

{ _id: 5cfd15eacf0cee3f14f5bb85,
  news_id: 2,
  title: '新闻2',
  author: 'joyitsai',
  words: 'qwertyuio',
  __v: 0 }
上一篇下一篇

猜你喜欢

热点阅读