0

I have a Mongoose schema called events which includes an array of vendors:

vendors: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Vendor"
      }   
   ],

I am trying to execute a query in URL search params on the first vendor in the array (i.e. vendors[0]). In my controller, I have the query structured like this:

    async eventIndexAll (req, res, next) {
        let queryArray = [];
        let queryObject = {};
        let { search, vendor } = req.query;
        
        if(vendor) queryArray.push({"vendors[0].id": vendor});

        if(search) {
            const regex = new RegExp(middleware.escapeRegex(search), 'gi');
            queryArray.push({name: regex});
        }
        if(queryArray.length) {
            queryObject['$and'] = queryArray;
        }

In my Event Index View I have tags displayed for vendors[0]:

<a href="/event/?vendor=<%- event.vendors[0].id %>">
   &nbsp&nbsp<span class="vendors-tag"><%- event.vendors[0].name %></span>
</a>

When I click on the tag, the URL search param looks correct (/event/?vendor=5f699ee13e4f99dddc746fd2), though it is not returning all the event records which include this vendor ID.

I assume this is because the event.vendors only INCLUDES this ID, rather than exactly EQUALS it, but I'm unsure how I can perform a query like this in URL search params. Can anyone advise what I'm doing wrong please?

PYP
  • 125
  • 13

0 Answers0