Skip to content Skip to sidebar Skip to footer

Mongoosejs/mongodb Search Exact Phrase

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

Solution 1:

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.

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: newRegExp(term, regexFlags)};

Model[method]({
    keyword: query
}).exec().then(function(result) {
    // do stuff with `result`
}, function(err) {
    // handle `err`
});

Post a Comment for "Mongoosejs/mongodb Search Exact Phrase"