Reputation: 568
I'm trying to do a full-text search in MongoDB in two fields (body and title).
Model:
var newsSchema = new mongoose.Schema({
title: String,
body: String,
tags: Array,
date: Date
});
newsSchema.index({body: 1, title: -1});
var newsModel = mongoose.model('News', newsSchema);
Request:
var search_text = 'test';
newsModel.find({
$text: {
$search: search_text
}
}).then((news) => {
res.send(JSON.stringify(news));
}).catch((err) => {
res.send(JSON.stringify(err));
});
But I get an error text index required for $text query
. What is the problem?
MongoDB version 3.2.8.
Upvotes: 0
Views: 195
Reputation: 1228
You need to create a text index for the field that you're trying to query. See this https://docs.mongodb.com/v3.2/core/index-text/#create-text-index for more info. Also see this file https://github.com/gabesoft/dask/blob/master/components/rss/post-model.js from one of my projects on how to create a text index in mongoose
Upvotes: 1