4
votes

I need to perform a text search inside array elements. Is it possible?

Using Mongoose in Node.js and my userSchema looks like:

{
 _id: "123456",
 name: "Lucas"
 items: [
  { title: "Shoes", description: "Very nice shoes"}, 
  { title: "Pants", description: "Great pants!"}
 ]
}

I tried to add the indexes like this:

userSchema.index({ "items.title": "text", "items.description": "text" });

But the following query returns nothing:

User.find({  $text: { $search: "Shoes" }});
1
It work fine when tried from mongo shell. The text search on "Shoes" will match both the title and description fields, where the text values "Shoes" and "... nice shoes" are the matches. - prasad_
Can you return any records? e.g. try User.find() - DevKyle

1 Answers

2
votes

mongoose isn't an index management solution. So don't rely on mongoose to create indexes. They even state this on their docs at faq.

In a production environment, you should create your indexes using the MongoDB shell rather than relying on mongoose to do it for you.

So all you need to do is creating the text index at mongodb shell. If the collection name is different from users you need to change also below.

db.users.createIndex(
    {
        "items.title": "text",
        "items.description": "text",
    }
)