1

I have setup a before hook so that if a query param of search is present a custom Mongoose aggregation query is run to find Orders by customer details like...

module.exports = function(hook, next) {
  if (hook.params.query && hook.params.query.search) {
  let search = hook.params.query.search;
  let regEx = new RegExp(".*" + search + ".*", "i");
  delete hook.params.query.search;

  const OrderModel = hook.app.service("orders").Model;
  OrderModel.aggregate([
  {
    $lookup: {
      from: "customeraddress",
      localField: "shipping_address",
      foreignField: "_id",
      as: "shipping_address"
    }
  },
  {
    $lookup: {
      from: "customeraddress",
      localField: "billing_address",
      foreignField: "_id",
      as: "billing_address"
    }
  },
  {
    $match: {
      $or: [
        {
          "shipping_address.first_name": regEx
        },
        {
          "shipping_address.last_name": regEx
        },
        {
          "shipping_address.email": regEx
        },
        {
          "billing_address.first_name": regEx
        },
        {
          "billing_address.last_name": regEx
        },
        {
          "billing_address.email": regEx
        }
      ]
    }
  }
]).then(orders => {
  hook.result = orders;
  next();
});
} else {
next();
}
};

which works fine in the sense that it returns the orders, but the problem is I lose the attributes on the result for pagination which would normally be

{
  "total": 2453,
  "limit": 25,
  "skip": 0,
  "data": []
}

So how can I do a custom query like this whilst maintaining the same response structure. Is this something I need to do myself or is there an alternative way of doing it.

dottodot
  • 1,479
  • 1
  • 16
  • 24

1 Answers1

1

That is to be expected because you are using directly the mongoose Model for that service.

The service find method is the one generating those extra info. It does a count to give you total. Then limit and skip is from your filters. That is why if you do $paginate false then you will only get an array of data without those total, skip, limit.

You can do a count by doing yourservice.find({query: {...,$limit: 0}}) or with your aggregate, you need to do something like this.

So you need to do it yourself.

Jalil
  • 440
  • 4
  • 15