sir_thursday sir_thursday - 4 months ago 29
Javascript Question

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" } })

Answer

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

});