为什么我计算总数时得到 null?

huangapple go评论72阅读模式
英文:

Why am i getting null for calculating a total?

问题

以下是您要翻译的内容:

我有以下的销售模型

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;

我想要找到所有的销售并累积总金额属性。所以我想要计算所有销售所产生的总金额。

这是我的方法:

//@desc      获取所有销售的总金额
//@method    GET
//@access    私有

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

  if (!sales) {
    return next(new ErrorResponse(`未找到销售`));
  }

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

  console.log(total);

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

昨天之前,我的方法一直正常工作,但现在我在响应中得到以下内容:

success: true,
total: null

我已经在控制台中记录了 total,但我得到了 NaN,但是我的所有销售都将总金额设置为数字,而不是字符串或其他类型的数据。

我没有更改我的方法,逻辑似乎没有问题。是否有任何原因导致我得到了 null?

英文:

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?

答案1

得分: 1

这看起来像是有人偷偷将一个文档添加到您的集合中,其中total属性的值不是数字。当尝试查询这些文档时,Mongoose会尝试将该文档解析为数字,但无法成功,导致结果为NaN

在尝试对值求和时,与NaN相加的任何值都将导致结果为NaN,这将显示出这种确切的行为。

也许您可以检查一下您的集合,看看是否有任何文档不符合您的模式,例如total属性设置为除数字以外的任何内容。您的MongoDB集合可能不会关心这一点,所以我猜这很可能是根本原因。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月4日 22:38:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定