数据校验

2019-12-06  本文已影响0人  Wrestle_Mania
const mongoose = require("./db");

const UserSchema = mongoose.Schema({
  name: {
    type: String,
    trim: true,
    required: true
  },
  age: {
    type: Number,
    max: 100,
    min: 20,
    get(params) {
      return ++params;
    }
  },
  status: {
    type: String,
    default: "1",
    enum: ["0", "1", "2"]
  },
  phone: {
    type: String,
    match: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
  },
  index: {
    type: String,
    default: "123456",
    maxlength: 20,
    minlength: 10
    // index: true
  },
  hobby: {
    type: String,
    // 自定义的校验
    validate: function(params) {
      return params.split(":")[1] !== "烫头";
    },
    set(params) {
      return `我的爱好是:${params}`;
    }
  }
});

UserSchema.statics.findBySn = function(sn, cb) {
  this.find({ sn }, cb);
};

const UserModel = mongoose.model("User", UserSchema, "user");

module.exports = UserModel;
const UserModel = require("./model/user");

const user = new UserModel({
  name: "Cercei",
  age: 20,
  hobby: "烫头",
  status: "2",
  index: 12121211212121,
  phone: "17606529568"
});

user.save(err => {
  if (err) {
    console.log(err);
    return;
  }
  console.log("数据新增成功");
});
上一篇 下一篇

猜你喜欢

热点阅读