David Watson
David Watson

Reputation: 51

Can't canonicalize query: IndexNotFound: text index required for $text query', code: 17287

The error is triggered in the Product.find statement below:

var bodyparser = require('body-parser');
var express = require('express');
var status = require('http-status');
var _ = require('underscore');
var mongoose = require('mongoose');
var productSchema = require('./product');

var schema = new mongoose.Schema(productSchema);

schema.index({ name: 'text' });

module.exports = function(wagner) {
var api = express.Router();

 api.use(bodyparser.json());

 api.get('/product/text/:query', wagner.invoke(function(Product) {
 return function(req, res) {
  console.log("we are  in the get " + req.params.query);
  Product.
    find(
      { $text : { $search : req.params.query } },
      { score : { $meta: 'textScore' } }).
    sort({ score: { $meta : 'textScore' } }).
    limit(10).
    exec(handleMany.bind(null, 'products', res));
  };
}));

return api;
};
function handleMany(property, res, error, result) {
 console.log("We are handling the many");
 if (error) {
  console.log(error);
  return res.
  status(status.INTERNAL_SERVER_ERROR).
  json({ error: error.toString() });
 }

 var json = {};
 json[property] = result;
 res.json(json);
}

I'm running MongoDB 3.4.2 on windows 10. I explicitly ran the statement db.products.ensureIndex({name: "text"}); in the MongoDB shell and for the first time I didn't get the error. It still gets timeout errors intermittently, though, when the query takes more than 2000 ms. I thought that I didn't have to explicitly add an index in the MongoDB shell because I'm putting on a schema index in the above code, but I don't know for sure.

Thanks,

William

Upvotes: 2

Views: 939

Answers (1)

David Watson
David Watson

Reputation: 51

I got into the MongoDB shell and put the index on the products collection like this:

db.products.createIndex({name: "text"})

That was my solution, and it worked, but I don't know if there was a glitch somewhere that made that solution necessary.

Upvotes: 3

Related Questions