1
User.find({
        $or:[
            {'userSetData.name': { $regex: new RegExp( searchTerm ,'i') }},
            {'local.email': { $regex: new RegExp( searchTerm ,'i') }},
            {'google.name': { $regex: new RegExp( searchTerm ,'i') }},
            {'google.email': { $regex: new RegExp( searchTerm ,'i') }},
            {'facebook.name': { $regex: new RegExp( searchTerm ,'i') }},
            {'facebook.email': { $regex: new RegExp( searchTerm ,'i') }}
        ]
    }, function(err, doc) {
        if( err ){
            console.log( err );
        }
        return doc;
    });

The above query fetches any user whose email or name matches the searched criteria. However as expected it returns the entire doc of the user found..

http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/ On the mongodb site they demonstrate the use of the projection to limit the fields of the doc returned, eg:

db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )

Is it possible to combine an $or from mongoose with the projection option of mongo, or is post processing the only option?

1 Answers1

1

You should be able to pass another object to your find and use projections

User.find({
    $or:[
        {'userSetData.name': { $regex: new RegExp( searchTerm ,'i')    
    }},
        {'local.email': { $regex: new RegExp( searchTerm ,'i') }},
        {'google.name': { $regex: new RegExp( searchTerm ,'i') }},
        {'google.email': { $regex: new RegExp( searchTerm ,'i') }},
        {'facebook.name': { $regex: new RegExp( searchTerm ,'i') }},
        {'facebook.email': { $regex: new RegExp( searchTerm ,'i') }}
    ]
}, {<projection goes here>},
 function(err, doc) {
    if( err ){
        console.log( err );
    }
    return doc;
});

source http://mongoosejs.com/docs/api.html#model_Model.find

ThrowsException
  • 2,586
  • 20
  • 37
  • I also found this for anyone playing with mongo for the first time: http://stackoverflow.com/questions/12096262/how-to-protect-the-password-field-in-mongoose-mongodb-so-it-wont-return-in-a-qu –  Jun 01 '15 at 00:24