Mongoose casting of empty string to ObjectId

762 views
Skip to first unread message

Martín Paulucci

unread,
May 23, 2013, 10:23:57 AM5/23/13
to mongoo...@googlegroups.com
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! 




Aaron Heckmann

unread,
May 23, 2013, 6:47:48 PM5/23/13
to mongoo...@googlegroups.com
On Thu, May 23, 2013 at 7:23 AM, Martín Paulucci <martin.c...@gmail.com> wrote:
- Is it expected behavior to get a casting error with an empty String? My milestone property is optional...

Yes
 
- 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. 

Good idea. If you have a good one in mind please open a pull request so we can add it to the docs.
 
- What is a good approach to solving this issue? 
Reply all
Reply to author
Forward
0 new messages