Hi, I have this in my schema:
milestone: {type: ObjectId}
A optional milestone property that is an ObjectID. When I get a POST with no milestone, in my JSON object I get {.. milestone: "", ...}. When trying to save it, I get this error:
{ message: 'Cast to ObjectId failed for value "" at path "milestone"',
name: 'CastError',
type: 'ObjectId',
value: '',
path: 'milestone' }
I've tried fixing this with a validate middleware:
Foo.schema.pre 'validate', (next) ->
if this.milestone == ""
delete this.milestone
next()
But apparently the validate middleware is never reached because it is called after the casting, so I keep getting the error.
A couple of questions/comments:
- Is it expected behavior to get a casting error with an empty String? My milestone property is optional...
- It would be nice to have a diagram or something in the docs about the middleware execution flow, like: 'default validation' -> 'custom pre validation middleware' -> 'custom pre save middleware'... At least for me, I thought that my validation middleware would execute before the casting.
- What is a good approach to solving this issue?
Thanks! BTW, Mongoose is awesome!