5

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" }});
2
  • 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. Commented Apr 3, 2020 at 3:57
  • Can you return any records? e.g. try User.find() Commented Apr 3, 2020 at 4:57

2 Answers 2

2

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",
    }
)
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! Perfect!
0

For me it worked with @typegoose index decorator.

@index({
    _id: "text",
    name: "text",
    items: "text",
    "items.title": "text",
    "items.description": "text",
})
export class User {
    @prop({ required: true }) public name: string;
    @prop({ required: true }) public items: Array<ItemInterface>;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.