Ashis Jena
Ashis Jena

Reputation: 450

mongoose validator for "required:true" is not working

Mongoose validator is failing to validate where it's "required:true".

Sample code for mongoose schema and model

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
let chargingLocationSchema = new Schema({
  values: {
    type: Array,
    required: [true, 'Why no values? Always provide values!']
  },
  chargingHours: {
    type: Number,
    min: 0.1,
    max: [24, 'There is only 24 hours in a day']
  }
}, {
  collection: 'charging_locations'
});

module.exports = mongoose.model('ChargingLocations', chargingLocationSchema);

Mocha test cases for mongoose validation testing

const expect = require('chai').expect;
const ChargingLocations = require('../chargingLocationsModel');

describe('ChargingLocationsModel', () => {
  it('should be invalid if values is empty', (done) => {
    let cl = new ChargingLocations();

    cl.validate((err) => {
      expect(err.errors.values).to.exist;
      done();
    });
  });

  it('charging hours should be within 24', (done) => {
    let cl = new ChargingLocations({ "chargingHours": 30 });

    cl.validate((err) => {
      expect(err.errors.chargingHours).to.exist;
      done();
    });
  });
});

Mongoose version:

mongoose": "^5.1.3

Error, as it's not making "values" as compulsory:

ChargingLocationsModel
    1) should be invalid if values is empty
    √ charging hours should be within 24


  1 passing (35ms)
  1 failing

  1) ChargingLocationsModel
       should be invalid if values is empty:
     Uncaught TypeError: Cannot read property 'errors' of null
      at cl.validate (tests\schema.specs.js:9:18)
      at D:\nodeApp\node_modules\mongoose\lib\document.js:1522:5
      at complete (node_modules\mongoose\lib\document.js:1683:5)
      at p.doValidate.skipSchemaValidators (node_modules\mongoose\lib\document.js:1716:20)
      at D:\nodeApp\node_modules\mongoose\lib\schematype.js:800:11
      at _combinedTickCallback (internal/process/next_tick.js:131:7)
      at process._tickCallback (internal/process/next_tick.js:180:9)

Upvotes: 2

Views: 3168

Answers (1)

shmit
shmit

Reputation: 2524

This is because Mongoose type arrays have a default value of empty array. As per mongoose document, to override that define a default of undefined. Refer to mongoose documentation for arrays for details.

Upvotes: 2

Related Questions