0

I'm clearly not understanding the aggregate function in mongoose. I'm trying to query the productCode field and return all of the products. The code below returns the error;

Product.aggregate(...).search is not a function.

What am I doing wrong here? I'm using mongoose.

products = await Product.aggregate().search({
    text: {
      query: 'text_supplied',
      path: 'productCode'
    }
  });

Update Date

The text in the query comes from an input field. I want to return all the documents from the product collection that contain the text I pass from the input field. This is for an autocomplete dropdown on the client-side. For instance.

Text from input field: '1';

Mongodb Collection: Products

[
  {
    productCode: '1A'
  },
  {
    productCode: 'C1'
  },
  {
    productCode: 'C2'
  }
];

In this scenario, I want to return every product that contains '1'. There for it return '1A' and 'C1'

Doug
  • 14,387
  • 17
  • 74
  • 104
bp123
  • 3,217
  • 8
  • 35
  • 74

1 Answers1

1

The atlas search aggregation stage was only added to mongoose for version 5.10.0.

feat(aggregate): add Aggregate#search() for Atlas Text Search #9115

Regardless according to the use case your posted you don't want to be using a text but rather you want a regex search:

Product.aggregate([
   {
      "$search": {
         "regex": {
            "path": "productCode",
            "query": ".*1.*"
         }
      }
   }
])

I could explain further but this was not the original question, however I do recommend you read up some more on analyzers as their role in both the indexing and querying is pivotal.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • I'm not using Atlas. I think that's why this doesn't work. – bp123 Sep 30 '20 at 06:28
  • No it doesn't work because your mongoose version needs an upgrade, once you upgrade it you will get a different error saying you don't have an atlas text index which is one of the requirments. – Tom Slabbaert Sep 30 '20 at 06:32
  • Sorry, I did update and the error has changed to 'MongoError: Unrecognized pipeline stage name: '$search'' – bp123 Sep 30 '20 at 06:39
  • Atlas search does not work outside of atlas but in this case I'd go with regexp over full text search, thus this is the correct answer. – D. SM Sep 30 '20 at 17:34