我正在开发一个项目,用户可以在搜索框中输入他想从用户那里找到的任何内容。可以是姓名、卡号、用户名等。
mongoose.js 中有什么东西可以在所有字段 中找到一个字符串吗?
类似于:
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
});
我发现已经有一个选项与 RegEx 相匹配,但它仅适用于在一个字段中进行搜索。
感谢您的宝贵时间。
最佳答案
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
});
关于node.js - Mongoose.js 检查所有字段以匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381843/