These are chat archives for Automattic/mongoose

Sep 2018
Andrey Gazhala
Sep 16 2018 19:20
@lineus Thank you for help)
Maurizio Bellemo
Sep 16 2018 19:32

a question how to handle aggregated values. I have a parent object called customer and an embedded array of deals. Deals have money value associated, and I would to have an aggregated value at the customer level with the aggregated value from the deals. I was thinking about a virtual property, but it is not ok because I need to sort over it (sort over the customers that bring more value). Therefore, I created a post hook in Mongo to update the aggregate value whenever a new deal gets added, updated, removed.'findOneAndUpdate', function (customer, next) {
    if (customer && {
        const aggregation = (accumulator, deal) => {
                // formula not important
                return accumulator;

        Customer.updateOne({ _id: customer._id }, {
            $set: {
                aggregation:, 0)
        }).then(_ => {

So, what I do is that I perform another query to update the Customer object AFTER (post hook) the update in the deals has already been performed. As you can imagine, the result on the FE is a bit appalling because I get the new deal, but still the old aggregated value. If I refresh the total is correct. What would be the best solution to ensure that I get the aggregated value to the frontend?