Aggregate search function errors when executed

310 views Asked by At

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'

1

There are 1 answers

4
Tom Slabbaert On

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.