Filippo oretti
Filippo oretti

Reputation: 49817

Mongoose, nodejs, full text search

I am trying setting up a simple keywords full text search using Mongoose and nodejs, this is the code so far:

var db = mongoose.createConnection('localhost', config.mongoDbName)
    , ContSchema = Schema({
        'idUser': String,
        'title': String,
        'category': String,
        'slug': String,
        'description': String
      })
      .index({
      'title':'text',
      'description':'text'
    })
 , ContModel = db.model('Cont', ContSchema);

db.on('error', function (err) {

        console.error.bind(console, 'Mongoose connection error:' + err);
    });
    db.once('open', function () {

      process.stdout.write('Connection to mongodb db done...');
    });

then i do search query:

var getAllBy = function (limit, offset, keywords) {

       var sort
        , find
        , findScore;

       if (!!keywords) {

        find = {'$text':{'$search':keywords}};
        findScore = {'score':{'$meta':'textMatchScore'}};
        sort = {'score':{'$meta':'textMatchScore'}};

       } else {

        sort = {'_id':'desc'};
       }

       return new RSVP.Promise(function (resolve, reject) {

        ContModel.find(find, findScore).limit(limit).skip(offset).sort(sort).exec(function (err, data) {

          if (err){

            reject(err);
          } else {

            resolve(data);
          }
        });
       });
}

It doesnt work it returns this error in console: MongoError: Can't canonicalize query: BadValue bad sort specification

I am actually unable to find the real problem with this, can you please help me out?

thank you

Upvotes: 3

Views: 5094

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

Your keywords are incorrect here, see the correct syntax under the $meta operator, which currently only has "textScore":

  find = {'$text':{'$search':keywords}};
  findScore = {'score':{'$meta':'textScore'}};
  sort = {'score': {'$meta':'textScore'} }

Upvotes: 3

Related Questions