node.jsmongodbmongoose-plugins

Text search in MongoDB, keyword search


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.


Solution

  • 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.