1

I'm trying to do a keyword search in my mongoDB database. In the mongoDB console:

db.logs.find({$text: {$search: 'key1'}})

gives the correct result. But when I use mongoose-text-search on my nodejs controller I get an error. This is the definition of the schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var textSearch = require('mongoose-text-search');

var Log = new Schema({
    keywords: [String],
    description: String,
    videoId: String,
    logId: String,
    date: Date,
    robot: String
});

Log.plugin(textSearch);
Log.index({ keywords: 'text' });

module.exports = mongoose.model('log', Log);

and in the controller, at certain point I do:

Log.textSearch('key1', function(err,output) {
    if (err){
        res.send(500,err);
    } else {
        console.log(output);
    }           
});

and the response is:

{"name":"MongoError","message":"no such command: text","ok":0,"errmsg":"no such command: text","code":59,"bad cmd":{"text":"logs","search":"key1"}}

now, that message alone would make you think that text search is not working, but it is as I showed before. I'm running MongoDB shell version 3.0.2 so text search is enabled by default.

cauchi
  • 1,463
  • 2
  • 17
  • 45
  • 1
    That plugin was created using the old "db command form" of text searching before it was integrated into normal queries for MongoDB in 2.6. I believe that command is deprecated in MongoDB 3.0.x series. –  Jun 19 '15 at 09:56
  • That makes a lot of sense... so if I'm using mongoose, I should do a normal query? everywhere I find links and people recommending the usage of that plugin. – cauchi Jun 19 '15 at 10:00
  • Using the normal query form would be advised, if not only for it seems to be the method that is up to date with the supported methods on the server. –  Jun 19 '15 at 10:02

1 Answers1

0

For some reason I was having a hard time following moongose's documentation... as it turns out, this is very easy to do in a normal query (no need for a plugin). Just to give an idea of how it can be done (not my actual code but one used to test the idea)

router.get('/keywordsearch', function (req,res) {

        var query = Log.find();

        var findKeywords = [];
        if (req.query.keywords != '')
        {
            var words = req.query.keywords.split(",");

            for (ii=0; ii<words.length; ii++)
                findKeywords[ii] = {keywords: words[ii].trim()};

            console.log(findKeywords);
            query.or(findKeywords);
        }

        query.exec(function (err,logs) {
            if (err){
                res.send(500,err);
            } else {
                req.logsList = logs;

                res.render('searchdb',{user:req.user,logs:req.logsList});
            }
        });

});

which means you can do a keyword search using:

find({keyword: 'blablabla'})

and using the OR logical operator for many keywords.

cauchi
  • 1,463
  • 2
  • 17
  • 45