Validate manually, not on save?

182 views
Skip to first unread message

Nik Martin

unread,
Dec 6, 2013, 6:32:45 PM12/6/13
to mongoo...@googlegroups.com


I have a collection of documents with many many validators.  Users are allowed to edit documents (via web and mobile apps), and during this time the document is considered "open", so saves to the document are just to persist the document, it doesn't mean the user is done with it.  That happens when the user marks the document done via an attribute, which I check on every POST or PUT.  This means I only need to call Validate when the document has this attribute set.  Is there a way to do this, other than writing every validator as middleware?

Joe Wagner

unread,
Dec 12, 2013, 12:19:57 AM12/12/13
to mongoo...@googlegroups.com
Hey Nik,
I have a couple ideas, but I'm not sure if either will work for you.

If the document already exists and you don't want the validators ect to run, you could use one of mongoose's wrappers for findAndModify, e.g. Model.findByIdAndUpdate.
This would skip validation as well as pre and post middleware, but if you just want to persist the document that might be okay.

You could add a line to the beginning of the necessary validators that checks if the document is open, e.g.
Model.schema.path('name').validate(function (val) {
    if (this.open) { return true;  }
    // otherwise do validation...

This is sort of like writing every validator as middleware, but validators are basically internal middleware.

-Joe

Nik Martin

unread,
Dec 12, 2013, 9:39:32 AM12/12/13
to mongoo...@googlegroups.com
Joe,

Thanks for the suggestions.  What I think I might do is a combination of the methods you mentioned. In the top of each validator I have a check to see if the 'save' attribute is true, which is an application level save.  If is not, the validator just returns true.  I will also call findByIdAndUpdate if the field is not set, vs save if it is.


Nik 
Reply all
Reply to author
Forward
0 new messages