0

I have the following Schema set up on mongoose

{
    _id:
    store:
    offers:[{
        name:
        price:
    }]
}

I decided to indexed offers.name as follows

uniSchema.index({'offers.name':'text'});

and now I'm trying to do searches on that index

Stores.find({$text:{$search:VALUE}}, callback);

But this way whenever there's a hit on the search the whole store is listed, and I'm unable to figure out from which offer the match came from.

Is there a way to do this with indexes on mongoose? Figuring out which array element matched the query?

Lucas C. Feijo
  • 1,002
  • 3
  • 13
  • 29

1 Answers1

0

I'm not sure that's possible with a $text index.

With a straight query you can use a projection to do the same:

> db.array_find.find({ "offers.name": "firstname"},{"offers.$" : 1} )

But the text query doesn't reference the array directly so offers.name is not able to be used in the projection.

> db.array_find.find({ $text: { $search: "firstname"} },{"offers.$" : 1} )
error: {
    "$err" : "Can't canonicalize query: BadValue Positional projection 'offer.$' does not match the query document.",
    "code" : 17287
}

The problem with attempting any type of post processing of the array from a result document is your not going to be using mongo's text indexing but some approximation of it.

You may need a different data structure

_id:
store: 2
offer: 
  name: this is a single offer
  price: 4

_id:
store: 2
offer:
  name: this is the next offer
  price: 5
Matt
  • 68,711
  • 7
  • 155
  • 158