These are chat archives for Automattic/mongoose

Nov 2016
Ben Fletcher
Nov 23 2016 05:08
Very basic question -- where is the appropriate place to validate data type being a string and not a number cast to a string? That is I want to allow "42", but error on 42. If I do it in the schema, I need to set the type to Mixed to prevent casting pre-check but I feel like sticking with the String type since the data will indeed always be a string. I am leaning towards using a schema.pre method but wanted to get some feedback on that approach before going too far down that road if discouraged or just plain wrong. Many thanks as I work to learn the basics here -- apologies if this is addressed in the docs or on SO, I have spent 3-4 hours on this today and just don't know where to go next.
Henrik Lundgren
Nov 23 2016 08:01
@numbergames Have you tried custom validator,
amount: {
  type: String,
  validate: {
    validator(value) {
      return typeof value !== 'string';
Chris Klanac
Nov 23 2016 11:27
@henriklundgren I don't think a custom validator will work because, I think, the value has already been cast to a String by the time it runs.
Nov 23 2016 12:16
Hi, everyone. Is there a way to get and save data to specific subdocument in mongoose?
Ben Fletcher
Nov 23 2016 14:53
@cklanac @henriklundgren Correct -- confirmed with a log of the value type inside the validator. 42 has already had .toString applied by the time the validator runs.
Ben Fletcher
Nov 23 2016 17:46
Is there perhaps an undocumented typecast: false flag available that would skip the type coercion? Looking at the source code, from what I can see the .toString() is done based solely on the field type. Or to go back to the original question -- what's the best way or place to do type validation for pre-cast values?
Michael Leanos
Nov 23 2016 21:17
@numbergames I don't see why putting this in a pre('validate') routine wouldn't work or be appropriate. I don't know much about the pre-casting, so it's feasible that this has be cast as string even before the pre('validate') runs.
Ben Fletcher
Nov 23 2016 23:21
@mleanos Thanks! Will go that route.