I' m trying to emuluate with Mongoose a fulltext search into two fields. I' ve spent most of the day testing several query types but I' ve always failed. The MongoDB shell query is this one:
db.feeds.item.find({lang:"en", $or:[{title: /searchexpression/}, {body: /searchexpression/}] })
In this example I want to return only english documents that matches the search expression (including a regex) in title or body fields or in both fields. This query works, but the problem starts, as I said, when trying to adapt it with Mongoose, :-(
Some expressions that I used and that didn' t work:
exports.fullTextSearch = function(lang, text, callback) {
MyModel.find({lang:lang, $or: [{title:/text/},{body:/text/}]}).exec(callback);
MyModel.find({lang:lang, $or: [{title: new RegExp('\/'+text+'\/')}, {body:new RegExp('\/'+text+'\/')}]}).exec(callback);
MyModel.find({lang:lang}).or({title:/text/},{body:/text/}).exec(callback);
MyModel.find({lang:lang}).or({title:new RegExp('\/'+text+'\/')},{body:new RegExp('\/'+text+'\/')}).exec(callback);
}
Thank you very much!
Luis Cappa.
Haven't tested this, but according to the documentation this should work:
MyModel.find({lang:lang}).or([{title:/text/},{body:/text/}]).exec(callback);
Like your third example, but with the "or" conditions in an array.
EDIT:
To have the regex dynamic, use the fourth example, but with the "or" conditions in an array:
MyModel.find({lang:lang}).or([{title:new RegExp(text)},{body:new RegExp(text)}]).exec(callback);
Or define the regex outside :
var regexText = new RegExp(text)
MyModel.find({lang:lang}).or([{title:regexText},{body:regexText}]).exec(callback);