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" }});
CodePudding user response:
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",
}
)
CodePudding user response:
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>;
}