猫鼬查找查询不起作用,即使等效查询在mongodb上也可以正常工作 [英] Mongoose find query doesn't work even equivalent query works fine on mongodb
问题描述
我正在页面中实现标签系统.当用户输入任何字符串时,它将触发我的快速路由,并尝试查找键入的内容以填充列表,然后将其作为JSON返回以处理回调.问题出在moonggose上,因为该查询非常正确,而且如果我在mongo shell上执行该查询也可以正常工作.
查询:
var token = '/.*' + req.query.search + '.*/i';
Tag.find({ description: token , inactivatedAt: null }, function(err, tags) {
var tempArray = [];
if (tags) {
var counter = 0;
tags.forEach(function(tag) {
var dArray = [];
dArray.push(counter++);
dArray.push(tag.description);
dArray.push(null);
dArray.push(null);
tempArray.push(dArray);
});
}
res.writeHead(200, {'content-type': 'text/json'});
res.end(JSON.stringify(tempArray));
});
即使我以description: { $regex: token }
或description: token
进行查询,也找不到结果.相同的查询参数很好,并且可以从shell上的mongo中获取结果.例如:db.tags.find({ description: /.*MET.*/i , inactivatedAt: null }).pretty()
,但是我的猫鼬查询无效.
任何线索都将非常有帮助.预先感谢!
您需要将token
转换为正则表达式,而不仅仅是字符串:
var token = new RegExp(req.query.search, 'i');
I'm implementing a tag system in my page. When user entry any string it will trigger my express route and try to find the content typed to fill a list and return it as JSON to process the callback. The problem is about moongose, because the query is pretty right and works fine if I execute it on mongo shell.
The query:
var token = '/.*' + req.query.search + '.*/i';
Tag.find({ description: token , inactivatedAt: null }, function(err, tags) {
var tempArray = [];
if (tags) {
var counter = 0;
tags.forEach(function(tag) {
var dArray = [];
dArray.push(counter++);
dArray.push(tag.description);
dArray.push(null);
dArray.push(null);
tempArray.push(dArray);
});
}
res.writeHead(200, {'content-type': 'text/json'});
res.end(JSON.stringify(tempArray));
});
Even if I query as description: { $regex: token }
or description: token
the result is not found. The same query parameters are fine and brings result from the mongo on the shell. E.g.: db.tags.find({ description: /.*MET.*/i , inactivatedAt: null }).pretty()
but my mongoose query doesn't work.
Any clue will be very helpful. Thanks in advance!
You need to convert token
into a regular express instead of just a string:
var token = new RegExp(req.query.search, 'i');
这篇关于猫鼬查找查询不起作用,即使等效查询在mongodb上也可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!