MongoJS not returning data when searching with regular expressions

元气小坏坏 提交于 2019-12-08 04:53:27

问题


Node.js, mongojs, mongodb. I am searching through a list of skills using regular expressions. Here is my server code:

var nconf = require('nconf');
var db = require('mongojs').connect(nconf.get('mongolab:connection'), ['skills', 'users']);

app.get('/api/skill', function(req, res){
    console.log('searching for ' + req.query['q']);

    var query = '{name: /' + req.query['q'] + '/i}';
    console.log('query: ' + query);
    db.skills.find(query, function(err, data){
        console.log('returning ' + JSON.stringify(data));
        if(!err){
            res.writeHead(200, {'content-type': 'text/json' });
            res.write( JSON.stringify(data) );
            res.end('\n');
        }   
    });

});

I do have a value of "asp.net" in my list. Console log outputs this:

searching for .net
query: {name: /.net/i} 
returning []

I use MongoHub to connect to the same server/db, paste the statement in query field, and get back my record:

{
    "name": "asp.net",
    "description": "",
    "_id": {
        "$oid": "500b4aae14f7960e91000001"
    }
}

Any suggestions?


回答1:


query has to be an Object, not a string. Try this instead:

var query = {name: new RegExp(req.query['q'], 'i') };


来源:https://stackoverflow.com/questions/11597205/mongojs-not-returning-data-when-searching-with-regular-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!