sir_thursday
sir_thursday

Reputation: 5409

Mongoose text index on nested schema field

I have the following schema:

const Schema = ({
  metadata: {
    title: String,
    ...
  },
  ...

});

and I'm looking to create a a text index on metadata.title. I can create a text index successfully on any first level property, but I'm running into trouble with the nested title.

I've tried the following code, to no avail. Is my syntax wrong? I've had no luck with docs...

Schema.index({ 'metadata.title': 'text' });

Searching:

Schema
  .find(
    { $text : { $search : req.params.query } },
    { score : { $meta: "textScore" } })

Upvotes: 10

Views: 1320

Answers (3)

kabapy
kabapy

Reputation: 177

you may have to recreate the index with the new parameters or try to drop and recreate the collection

Upvotes: 0

sir_thursday
sir_thursday

Reputation: 5409

It turns out what I had originally was correct, as pointed out by @JohnnyHK. I must have had some other error that caused the index to not work...

Upvotes: 2

Amiram Korach
Amiram Korach

Reputation: 13286

const Schema = ({
  metadata: {
    title: {
      type: String,
      index: true
      }
    ...
  },
  ...

});

Upvotes: 0

Related Questions