I am trying to fetch results from mongodb using regular expressions. For example, while searching for a username amitverma
, I want to be able to get that result if i type amit
in the searchbox.
I have searched around the internet for a solution and everybody seems to have got it working by writing code like this:
var searchterm = req.body.name;
collection.find(
{ "username": new RegExp('/.*' + searchterm + '.*/') },
[ 'username', 'status' ],
function(e, docs){
console.log(e);
console.log(docs);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ 'docs' : docs }) );
res.end('\n');
}
);
I still cannot get it to work. It gives me an empty array. Also, after replaceing {username: searchterm}
to { "username": new RegExp('/.*' + searchterm + '.*/') }
, I can't even get results for the string amitverma
which means this regex thing is failing.
Try removing the slashes from the RegExp()
constructor:
{ "username": new RegExp('.*' + searchterm + '.*') },
The slashes should not be there, unless you are searching for two literal forward slashes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.