I'm having problems with inserting into mongoDB because good objects don't pass the mongoDB validator.
To make it worse, the error is a generic: Document failed validation which in a big multi-nested object can make things confusing regarding where exactly this validation fails.
myValidatorIs =
{ validator:
{ $jsonSchema :
{ bsonType: "object"
, required: [ "price" ]
, properties:
{ price:
{ bsonType: "double" // price needs to be a double, tried with decimal also.
, description: "must be a double/float and is required"
}
}
}
}
, validationAction: "error"
, validationLevel: "strict"
};
db.collection("collection").insertOne({ price : 4.5 }); // this works
db.collection("collection").insertOne({ price : 4.0 }); // this doesn't - see error below
ERROR: UnhandledPromiseRejectionWarning: MongoError: Document failed validation
My app needs something different but i simplified it here by using price.
Now after lots of trial and error i figured out what actually happens. Was not as clear as above.
Basically in javascript the 4.0 (float) is implicitly transformed to 4 (integer)
And this integer fails the validation since is not a float. Which is super wired. Since this data comes from outside, i can't control if is float or integer. Javascript only knows about number.
Is this indeed the problem? I mean i tried lots of different things and i can't see any other reason other then this implicit type conversion.
Because in the validator - if i set bsonType : "int" and i give it {price: 1} or {price: 4.0} then the insertion works with no errors.
How to deal with this type of issue? How to insert {price: 4.0}?
Also what settings should i include to make that description field i set to appear in the error message? After all what is the purpose of properties.price.description if not to create better error messages ?

NumberDecimalfunction like:db.collection("collection").insertOne({ price : NumberDecimal(4.0) });