MongooseJS/MongoDB 搜索精确短语 [英] MongooseJS/MongoDB search exact phrase
问题描述
我想让我的用户搜索确切的关键字,例如,用户被指示用引号将关键字括起来,例如Apple"只会搜索确切的关键字 Apple,而如果没有引号,它会搜索
I want to let my users search for exact keyword, for example the user is instructed to enclose keyword with quotes like "Apple" would only search for the exact keyword Apple, while without quotes it would search for
*Apple*
如何在 MongooseJS 中编写这些查询?我想我应该在字符串的开头和结尾查找引号?
How can I write these queries in MongooseJS? I suppose I should look for quotes in the beginning and end of string?
推荐答案
我认为您是对的,检查第一个和最后一个字符是引号可能是最简单的.然而猫鼬本身无法做到这一点.我建议事先准备查询并选择适当的find 方法.
I think you're right that checking the first and last characters are quotes is probably easiest. However mongoose itself cannot do this. I suggest preparing the query beforehand and also choosing the appropriate find method.
我们还可以使用 $regex
运算符来针对集合中每个文档的 'keyword' 属性执行给定的正则表达式.
We can also use the $regex
operator to perform the given regular expression against the 'keyword' property of each document in the collection.
var userInput = '"Apple"';
var term = userInput.trim();
var caseInsensitive = true; // = some user input?
var isExactTerm = (function() {
var firstChar = term[0];
var lastChar = term[term.length - 1];
return (firstChar === '"' && lastChar === '"');
}();
if(isExactTerm) {
// Remove quotes from the query
term = term.substr(1, str.length - 1);
}
var method = (isExactTerm) ? 'findOne': 'find';
var regexFlags = (caseInsensitive) ? 'i' : '';
var query = (isExactTerm) ? term : {$regex: new RegExp(term, regexFlags)};
Model[method]({
keyword: query
}).exec().then(function(result) {
// do stuff with `result`
}, function(err) {
// handle `err`
});
这篇关于MongooseJS/MongoDB 搜索精确短语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!