I want to make the title
and the description
field search-able.
I'm using node.js 6.9.1, mongoldb 3.2.11 and mongoose 4.7.1.
Schema:
const Schema = new mongoose.Schema({
...
title: { type: String, required: true, text: true },
description: { type: String, text: true }
...
})
But when I connect to the database just the title
field is added as a text index.
$ mongo
MongoDB shell version: 3.2.11
connecting to: test
> db.podcasts.getIndexes()
...
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "title_text",
"ns" : "test.podcasts",
"background" : true,
"weights" : {
"title" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
...
Using schema.index()
works as expected
const Schema = new mongoose.Schema({
...
title: { type: String, required: true },
description: { type: String }
...
})
Schema.index({ title: 'text', description : 'text' })
$ mongo
MongoDB shell version: 3.2.11
connecting to: test
> db.podcasts.getIndexes()
...
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "title_text_description_text",
"ns" : "test.podcasts",
"background" : true,
"weights" : {
"description" : 1,
"title" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
...
Schema.index()
is the preferred way to create a text index, using text: true
in individual fields is not recommended because text: true
on multiple fields will attempt to create multiple text indexes, which doesn't work in mongodb.
Most helpful comment
Schema.index()
is the preferred way to create a text index, usingtext: true
in individual fields is not recommended becausetext: true
on multiple fields will attempt to create multiple text indexes, which doesn't work in mongodb.