本文介绍了使用正则表达式搜索时,MongoJS不返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Node.js, mongojs ,mongodb.我正在使用正则表达式搜索技能列表.这是我的服务器代码:

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');
        }
    });

});

我的列表中确实有一个"asp.net"值.控制台日志输出:

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

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

我使用MongoHub连接到相同的服务器/数据库,将语句粘贴到查询字段中,并获取我的记录:

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"
    }
}

有什么建议吗?

推荐答案

query必须是一个Object,而不是字符串.尝试以下方法:

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

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

这篇关于使用正则表达式搜索时,MongoJS不返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 09:43