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

kkbh8khc  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(120)

我有以下销售模型

  1. const mongoose = require('mongoose');
  2. const SaleSchema = new mongoose.Schema({
  3. tickets: [
  4. {
  5. type: mongoose.Schema.Types.ObjectId,
  6. ref: 'Ticket',
  7. required: true,
  8. },
  9. ],
  10. total: {
  11. type: Number,
  12. required: true,
  13. },
  14. createdAt: {
  15. type: Date,
  16. default: Date.now,
  17. },
  18. });
  19. const Sale = mongoose.model('Sale', SaleSchema);
  20. module.exports = Sale;

字符串
我想找到我所有的销售额并累计总资产。所以我想计算所有销售的总收入。
这是我的方法:

  1. //@desc Get the total amount of all sales
  2. //@method GET
  3. //@access Private
  4. exports.getTotalSales = asyncHandler(async (req, res, next) => {
  5. const sales = await Sale.find();
  6. if (!sales) {
  7. return next(new ErrorResponse(`No sales found`));
  8. }
  9. let total = 0;
  10. sales.forEach((sale) => {
  11. total += sale.total;
  12. });
  13. console.log(total);
  14. res.status(200).json({
  15. success: true,
  16. total,
  17. });
  18. });


直到昨天我的方法工作正常,但现在我在我的React如下:

  1. success: true,
  2. total: null


我有控制台记录total,我得到NaN,但我所有的销售总额作为数字,而不是作为字符串或其他类型的数据。
我没有改变我的方法,逻辑似乎是好的。为什么我的总数为零?

mfuanj7w

mfuanj7w1#

对我来说,这看起来像是有人在你的集合中偷偷地放了一个文档,其中的total属性不是一个数字。当试图查询文档时,mongoose试图将此文档解析为一个数字,但无法这样做,结果是NaN
当尝试对这些值求和时,任何与NaN求和的结果都是NaN,这将显示这种确切的行为。
也许你可以检查你的收藏中是否有任何不符合你的模式的文档,例如。将total属性设置为不同于数字的任何值。您的MongoDB集合不会在意,所以我猜这肯定是这里的根本原因。

相关问题