Model.findByWhatever('whatever')
Creates a find query based on the value you are trying to find by. I mostly use use this to add "login with username or password" option. For example User.findByWhatever(username or email)
would turn into User.find({username: username})
or User.find({email: email})
based on some rules you define.
Install
npm install mongoose-find-by-whatever
How to use
Use like any other mongoose plugin and pass an array of rules as the 2nd argument. The order of the rules determines their precedence. A rule can be one of the following:
RegExp
to test against valueFunction
that will get passed the value"ObjectId"
will search by _id"*"
will match anything
var whatevers = propertyName: rule propertyName: rule ...;UserSchema;
Example
// Given a User modelvar UserSchema = mongoose; // define some finder rulesvar whatevers = email: /@/ // Regexp _id: 'ObjectId' // ObjectId { return value !== -1; } name:'*' // Everything; UserSchema;User = mongoose; User // Turns into User.find({email: 'bob@email.com'})User // Turns into User.find({_id: '52aa38f7bcd27e0200000024'})User // Turns into User.find({name: 'bob'})