Search code examples
node.jsexpressmongoose

Why am i getting null for calculating a total?


I have the following Sale model

const mongoose = require('mongoose');

const SaleSchema = new mongoose.Schema({
  tickets: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Ticket',
      required: true,
    },
  ],
  total: {
    type: Number,
    required: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

const Sale = mongoose.model('Sale', SaleSchema);

module.exports = Sale;

i want to find all my sales and accumulate the total property. So i want to calculate the whole total made from all sales.

And this is my method:

//@desc      Get the total amount of all sales
//@method    GET
//@access    Private

exports.getTotalSales = asyncHandler(async (req, res, next) => {
  const sales = await Sale.find();

  if (!sales) {
    return next(new ErrorResponse(`No sales found`));
  }

  let total = 0;
  sales.forEach((sale) => {
    total += sale.total;
  });

  console.log(total);

  res.status(200).json({
    success: true,
    total,
  });
});

Till yesterday my method was working fine, but now i am getting in my response the following:

success: true,
total: null

I´ve console logged total and i get NaN but all of my sales have the total as number and not as a string or other type of data.

I didnt change anything to my method and the logic seems to be fine. Is there any reason why am i getting null to in my total?


Solution

  • To me this looks like someone snuck a document in your collection, where the total attribute is anything different than a number. When trying query for the documents, mongoose try to parse this document to a number, but is not able to do so, resulting in NaN.

    When trying to sum up the values, anything summed up with NaN results in NaN, which would show this exact behavior.

    Maybe you can check your collection for any document, that doesn't follow your schema, e.g. having the total attribute set to anything different than a number. Your MongoDB collection would not care, so I guess this could definitely be the root cause here.