Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Boolean validation not useful if a String is provided

for easier validation of my input, I tried to ensure that a mongoose-document can only be created, if a specific field is set to true (This field, is of course always true, IF the document was actually created properly, that's for reporting reasons).

This is a simplified poc:

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/playground')

var Schema = mongoose.Schema

var TestSchema = new Schema({
  testField: {
    type: Boolean,
    required: true
  }
})

// Try to ensure, that testField can only be true
TestSchema
  .path('testField')
  .validate(function (testField) {
    return (testField === true || testField === 'true')
  }, 'Test-field must be true!');

var Test = mongoose.model('test', TestSchema);


var newDoc = Test({
  testField: 'some random string'
})

newDoc.save(function (err, newDoc) {
  (err) ? console.log(err): console.log('newDoc was created')
})

The problem is, that even though I am supplying a random string instead of a Boolean value or "Boolean string" (e.g. "false" or "true" instead of just false/true), the document is still being saved properly, with the flag set to true.

If I supply "false" or false, the validation works properly and throws an error.

Apparently, there is some sort of type-casting, before the validation (and apparently also the defaults-action) is actually being called. Is there a way for me to fix my validation, or do I have to check the object explicitly, before creating the Mongoose-Object?

This is mongoose 4.3.6.

like image 292
BenSower Avatar asked Jan 19 '16 10:01

BenSower


1 Answers

Here is a solution that borders on hackery, but it should work:

const mongoose = require('mongoose');

mongoose.Schema.Types.Boolean.convertToFalse = new Set([false]);
mongoose.Schema.Types.Boolean.convertToTrue = new Set([true]);

Remember to set these immediately after the first require, and keep an eye on the cache.

Relevant documentation: https://mongoosejs.com/docs/schematypes.html#booleans

Turns our Mongoose casts five different things to bool, even with strict schemas. Really grinds my gears.

like image 128
Stewii Avatar answered Nov 14 '22 11:11

Stewii