express-restify-mongoose
express-restify-mongoose copied to clipboard
Unable to see aggregation query result from contextFilter in outputFn
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);
}
Just to be sure, can you verify outputFn
is called after your aggregation query sets its result?
@Zertz yes, outputFn is being called after aggregation query sets its result, but the result there is just of simple model.find query
@Zertz Tried setting the result as req.erm.result = result;
manually too, but it doesn't work that way
Hi @Zertz, Anything I should be trying to access the aggregation result in outputFn, without having to explicitly set the result?
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);
}
@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?
Perhaps this can help?