MongooseJS/MongoDB search exact phrase MongooseJS/MongoDB search exact phrase mongoose mongoose

MongooseJS/MongoDB search exact phrase


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: new RegExp(term, regexFlags)};Model[method]({    keyword: query}).exec().then(function(result) {    // do stuff with `result`}, function(err) {    // handle `err`});