mongoose schema validation code example

Example 1: mongoose schema type

var schema = new Schema({
  name:    String,
  binary:  Buffer,
  living:  Boolean,
  updated: { type: Date, default: Date.now },
  age:     { type: Number, min: 18, max: 65 },
  mixed:   Schema.Types.Mixed,
  _someId: Schema.Types.ObjectId,
  decimal: Schema.Types.Decimal128,
  array: [],
  ofString: [String],
  ofNumber: [Number],
  ofDates: [Date],
  ofBuffer: [Buffer],
  ofBoolean: [Boolean],
  ofMixed: [Schema.Types.Mixed],
  ofObjectId: [Schema.Types.ObjectId],
  ofArrays: [[]],
  ofArrayOfNumbers: [[Number]],
  nested: {
    stuff: { type: String, lowercase: true, trim: true }
  },
  map: Map,
  mapOfString: {
    type: Map,
    of: String
  }
})

// example use

var Thing = mongoose.model('Thing', schema);

var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = Buffer.alloc(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.map = new Map([['key', 'value']]);
m.save(callback);

Example 2: mongoose schema

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }
}, {
    timestamps: true
})

const User = mongoose.model('User', UserSchema);

module.exports = User;

Example 3: mongoose validate example

// example AUTH SCHEMA

const mongoose = require('mongoose')
const bcryptjs = require('bcryptjs')
const findOrCreate = require('mongoose-findorcreate')
const validator = require('mongoose-validator')
const Schema = mongoose.Schema

const setAuthSchema = new Schema(
  {
    username: {
      type: String,
      trim: true,
      required: true
    },
    email: {
      type: String,
      lowercase: true,
      trim: true,
      validate: [
        validator({
          validator: 'isEmail',
          message: 'Oops..please enter valid email'
        })
      ],
      required: true
    },
    password: {
      type: String,
      minlength: 8,
      maxlength: 16,
      trim: true,
      required: true
    },
    authsc: {
      idsocial: {
        type: String,
        trim: true,
        default: null
      },
      username: {
        type: String,
        trim: true,
        default: null
      },
      fullname: {
        type: String,
        trim: true,
        default: null
      },
      email: {
        type: String,
        lowercase: true,
        trim: true,
        validate: [
          validator({
            validator: 'isEmail',
            message: 'Oops..please enter valid email'
          })
        ],
        default: null
      },
      gender: {
        type: String,
        trim: true,
        default: null
      },
      avatar: {
        type: String,
        trim: true,
        default: null
      },
      provider: {
        type: String,
        trim: true,
        default: null
      }
    },
    role: {
      type: String,
      trim: true,
      default: 'user'
    },
    isActive: {
      type: Boolean,
      trim: true,
      default: false
    }
  },
  { timestamps: true }
)

setAuthSchema.plugin(findOrCreate)

setAuthSchema.pre('save', function (next) {
  if (this.isModified('password')) {
    const salt = bcryptjs.genSaltSync(10)
    this.password = bcryptjs.hashSync(this.password, salt)
    return next()
  }
})

setAuthSchema.static('hashPassword', (password) => {
  if (password) {
    const salt = bcryptjs.genSaltSync(10)
    return bcryptjs.hashSync(password, salt)
  }
})

setAuthSchema.static('verifyPassword', (password, hash) => {
  if (password && hash) {
    return bcryptjs.compareSync(password, hash)
  }
})

const AuthSchema = mongoose.model('auth', setAuthSchema)
module.exports = { AuthSchema }

Example 4: requir mongoose

const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/name", { useUnifiedTopology: true, useNewUrlParser: true });