NodeJS 数据验证与清理

MongoDB数据库:

  1. 安装mongoose:npm i mongoose
  2. 安装validator:npm i validator

mongoose 创建 collection model,指定各个字段数据类型,提供最基本的验证。但是复杂的验证就需要使用 npm validator。
sample code:

const mongoose = require("mongoose");
const validator = require("validator");
mongoose.connect("mongodb://127.0.0.1:27017/task-manager-api", {
  useNewUrlParser: true,
  // useCreateIndex: true, not supported
});
// 创建一个名称为users的collection:姓名,email,密码,年龄
const User = mongoose.model("User", {
  name: {
    type: String,   // 姓名为字符串
    required: true,  // 必须提供
    trim: true,   // 修剪:删除字符串前后的空格
    default: "Anymonous", // 如果没有提供姓名,使用“Anymous”作为姓名
  },
  email: {
    type: String,  // email 为字符串
    required: true,  // 必须提供
    trim: true,   // 删除前后空格
    lowercase: true,  // 转换为小写字符串
    validate(value) {  // 合法性验证
      if (!validator.isEmail(value)) { // 使用validator !
        throw new Error("Email is not valid!");
      }
    },
  },
  password: {
    type: String,  
    required: true,
    minLength: 7,   // 密码长度大于等于7
    trim: true,
    validate(value) {  // 不允许密码中含有"password"字样
      if (value.toLowerCase().includes("password")) {
        throw new Error("Password should not contain 'password'!");
      }
    },
  },
  age: {
    type: Number,
    default: 0,  // age 非必要字段,不提供则设默认值0.
    validate(value) {
      if (value < 0) {  // 年龄不允许为负
        throw new Error("Age must be positve!");
      }
    },
  },
});

// 可以修改各个字段,使用valid和invalid 值进行测试:
 const me = new User({
   name: "Erin",
   password: "pass",
   email: "MYEmail@Mail.com",
   age: 21,
 });
 me.save()
   .then(() => console.log(me))
   .catch((error) => console.log(error));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值