express-restify-mongoose icon indicating copy to clipboard operation
express-restify-mongoose copied to clipboard

Unable to see aggregation query result from contextFilter in outputFn

Open Khushboo-Mulani opened this issue 4 years ago • 7 comments

Hi @florianholzapfel,

Although aggregation query executes and gives result in contextFilter, I am unable to access the same result in outputFn(req.erm.result). Here is the code snippet of contextFilter function:

contextFilter: function (model, req, next) {
	if (req.aggregationQuery) {
	        model.aggregate(req.aggregationQuery).then((result) => {
		    req.erm.result = result;   //here the result of aggregation query is seen correct
		    next(model)
	      })
        }
   }

Wherein, aggregationQuery has been added in request object in the preRead hook in this case.

Expectation:

     outputFn: (req, res, next) => {
          const result = req.erm.result;   //here the result should be the result of aggregation query
          const statusCode = req.erm.statusCode;
          res.status(statusCode).json(result);
     }

Khushboo-Mulani avatar Nov 06 '20 14:11 Khushboo-Mulani

Just to be sure, can you verify outputFn is called after your aggregation query sets its result?

Zertz avatar Nov 06 '20 18:11 Zertz

@Zertz yes, outputFn is being called after aggregation query sets its result, but the result there is just of simple model.find query

Khushboo-Mulani avatar Nov 08 '20 06:11 Khushboo-Mulani

@Zertz Tried setting the result as req.erm.result = result; manually too, but it doesn't work that way

Khushboo-Mulani avatar Nov 08 '20 06:11 Khushboo-Mulani

Hi @Zertz, Anything I should be trying to access the aggregation result in outputFn, without having to explicitly set the result?

Khushboo-Mulani avatar Nov 09 '20 16:11 Khushboo-Mulani

The result you are setting in contextFilter gets overriden shortly after when the query runs.

I'm not sure exactly what you're trying to achieve but this should work:

contextFilter: function (model, req, next) {
  if (req.aggregationQuery) {
    model.aggregate(req.aggregationQuery).then((result) => {
      req.erm.aggregationResult = result;
      next(model)
    })
  }
}

outputFn: (req, res, next) => {
  const result = req.erm.aggregationResult;
  const statusCode = req.erm.statusCode;
  res.status(statusCode).json(result);
}

Zertz avatar Nov 09 '20 16:11 Zertz

@zerts the find query shouldn't run at all in the first place when aggregate query is present and executed. How can I stop that from happening?

In my case, for a request, first aggregation query is executed, the result of which we are assigning to "req.erm.aggregationResult", then find query also executes for the same request.

Is model we are passing to callback in "next(model)" executing the find query, if yes, how can that behaviour be changed?

Khushboo-Mulani avatar Nov 10 '20 10:11 Khushboo-Mulani

Perhaps this can help?

Zertz avatar Nov 10 '20 14:11 Zertz