nodejs操作mongodb之五(数据校验)

一、数据校验的介绍

mysql数据库层面中常见的数据校验,非空字段

二、mongoose中自带的数据校验

  • 1、required表示这个数据必须传入
  • 2、max用于Number类型数据,允许的最大值
  • 3、min用于Number类型数据,允许的最小值
  • 4、enum枚举类型,要去数据必须满足枚举值里面的其中一个
  • 5、match增加数据必须符合match的正则规则
  • 6、maxlength最大长度
  • 7、minlength最小长度

三、在schema中使用数据校验

  • 1、定义schema

    const mongoose = require('./db');
    
    const userSchema = mongoose.Schema({
        name: {
            type: String,
            require: [true, '此项为必填内容'], // 需要自己去写获取其中的错误
            minlength: [3, '名字最小长度为3'],
            maxlength: [10, '名字最长为10'],
        },
        age: {
            type: Number,
            max: 150,
            min: 0,
        },
        status: {
            type: String,
            enum: ['0', '1', '2']
        },
        phone: {
            type: Number,
            match: /^1[3456789]\d{9}$/
        }
    })
    
    module.exports = mongoose.model('User', userSchema, 'user');
    
  • 2、增加数据的时候数据校验

    const UserModel = require('./model/user');
    
    const user = new UserModel({
        name: '李四',
        age: 20,
        status: 3,
        phone: 181706066
    });
    
    user.save((err) => {
        if (err) {
           console.log('-------遍历全部的错误开始---------')
           Object.keys(err.errors).forEach(item => {
               console.log(err.errors[item].message);
           })
           console.log('-------遍历全部的错误结束---------')
        } else {
            console.log('增加数据成功');
        }
    });
    

四、自定义校验器

  • 1、在schema中定义

    const mongoose = require('./db');
    
    const userSchema = mongoose.Schema({
        address: {
            type: String,
            require: true,
            // 方式一:简单定义
            // 自定义的验证器,如果通过验证返回 true,没有通过则返回 false
            // validate: function (desc) {
            //     return desc.length >= 10;
            // },
            // 方式二:需要定义错误提示的方式
            validate: {
                validator: function(desc) {
                    return desc.length >= 10;
                },
                message: '长度必须大于10',
            }
        }
    })
    
    module.exports = mongoose.model('User', userSchema, 'user');
    
  • 2、校验和上面的一样的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Node.js提供了许多不同的方式来操作MongoDB数据库。以下是其中一些常见的方法: 1.使用官方的MongoDB Node.js驱动程序 可以使用官方的MongoDB Node.js驱动程序来连接和操作MongoDB数据库。这个驱动程序提供了许多不同的方法和选项,可以满足不同的需求。以下是一个简单的例子,展示如何使用官方驱动程序连接到MongoDB数据库,并执行简单的查询操作: ``` const MongoClient = require('mongodb').MongoClient; // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, client) { console.log("Connected successfully to server"); const db = client.db(dbName); // Find some documents db.collection('users').find({}).toArray(function(err, docs) { console.log("Found the following records"); console.log(docs); client.close(); }); }); ``` 2.使用Mongoose库 Mongoose是一个MongoDB对象模型工具,它提供了一种更简单的方式来操作MongoDB数据库。它允许您定义模式和模型,以便更轻松地执行常见的操作,如插入、更新和查询文档。以下是一个例子,展示如何使用Mongoose连接到MongoDB数据库,并定义一个简单的用户模型: ``` const mongoose = require('mongoose'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database mongoose.connect(url, {useNewUrlParser: true}); // Define a schema const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); // Define a model const User = mongoose.model('User', userSchema); // Create a new user const user = new User({ name: 'John Smith', email: 'john@example.com', age: 30 }); // Save the user to the database user.save(function(err) { if (err) throw err; // Find all users User.find(function(err, users) { if (err) throw err; console.log(users); mongoose.connection.close(); }); }); ``` 3.使用第三方库 除了官方驱动程序和Mongoose之外,还有许多其他的Node.js库可以用于操作MongoDB数据库。一些流行的库包括MongoDB Native、mongojs和Monk。这些库提供了不同的API和功能,可以满足不同的需求。以下是一个例子,展示如何使用mongojs库连接到MongoDB数据库,并执行简单的查询操作: ``` const mongojs = require('mongojs'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database const db = mongojs(url, ['users']); // Find all users db.users.find(function(err, users) { if (err) throw err; console.log(users); db.close(); }); ``` 无论您选择使用哪种方法,Node.js提供了许多选项和库,可以帮助您轻松地操作MongoDB数据库。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值