Средство проверки Mongoose не может проверить, где оно «требуется: истина».
Пример кода для схемы и модели mongoose
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 для проверки достоверности mongoose
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:
mongoose": "^5.1.3
Ошибка, поскольку "значения" не являются обязательными:
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)