Reputation: 459
I'm working on a proyect where the user can type in a searchbox whatever he wants to find from an user. It can be a name, a card ID, an username, etc.
Is there anything in mongoose.js to find in all fields a string?
Something like:
var user_input = "le";
Users.find({$contains: user_input}, function(error, usersFound){
if(!error) console.log('I found users!', usersFound);
//usersFound contains all the users that has "le" in at least one field
});
I found already that there's an option that matches a RegEx but that's only for searching in one field.
Thank you for your time.
Upvotes: 3
Views: 1913
Reputation: 3809
var user_input = new RegExp("le", 'i');
var queryArray = [];
for (var property in Users.schema.paths) {
if (Users.schema.paths.hasOwnProperty(property) && Users.schema.paths[property]["instance"] === "String") {
queryArray.push(JSON.parse('{\"' + property + '\": \"' + user_input + "\"}"))
}
}
var query = {
$or: queryArray
};
Users.find(query, function(error, usersFound){
if(!error) console.log('I found users!', usersFound);
//usersFound contains all the users that has "le" in at least one field
});
Upvotes: 2