首页 > 解决方案 > 在计算字段 Mongoose 上的路径中,值“NaN”(类型编号)转换为数字失败

问题描述

在我的架构中,我添加了 3 个非必需参数ratingstotalRating用于自动计算averageRating。更新现有记录时,一切顺利,但单参数记录创建失败,出现Product.create error: Error: Product validation failed: averageRating: Cast to Number failed for value "NaN" (type number) at path "averageRating". 我尝试在请求正文中添加ratingsandtotalRating并将其默认设置为 0 但没有帮助。仍然收到错误。你能看出为什么吗??

架构:


const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    createdOnDate: { type: Number, required: true },
    name: { type: String, required: true },
    brand: { type: String, required: true },
    price: { type: Number, required: true },
    description: { type: String, required: true },
    category: { type: String, required: true },
    city: { type: String, required: true },
    region: { type: String, required: true },
    country: { type: String, required: true },
    vendor: { type: String, required: true },
    barcode: { type: String, required: true },
    imageUrl: { type: String, required: true },
    fullImages: { type: Array, required: true },
    thumbNails: { type: Array, required: true },
    // productImage: Uint8Array,
    minimumStock: { type: Number, required: true },
    availableQuantity: { type: Number, required: true },
    soldQuantity: { type: Number, required: true },
    totalRating: { type: Number, required: false, default: 0 },
    ratings: { type: Number, required: false, default: 0 },
    averageRating: {
        type: Number, required: false, default: function () {
            return (this.totalRating / this.ratings)
        }
    },

},
    { timestamps: true });

module.exports = mongoose.model('Product', productSchema, 'Products');

发送json:

Mongoos createProduct req.body:  {
  name: 'someName',
  quantity: 5,
  price: 5.5,
  city: 'Bologna',
  region: 'Emilia-Romagna',
  country: 'Italy',
  category: 'bikes',
  vendor: 'zazza zenigata',
  createdOnDate: 132468754,
  availableQuantity: 5,
  soldQuantity: 0,
  minimumStock: 10,
  imageUrl: 'someUrl',
  barcode: 'someCode',
  description: 'someDescription',
  brand: 'someBrand',
  totalRating: 0,
  ratings: 0
}


错误:

Product.create error: Error: Product validation failed: averageRating: Cast to Number failed for value "NaN" (type number) at path "averageRating"
    at ValidationError.inspect (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/error/validation.js:47:26)
    at formatValue (node:internal/util/inspect:757:19)
    at inspect (node:internal/util/inspect:336:10)
    at formatWithOptionsInternal (node:internal/util/inspect:1999:40)
    at formatWithOptions (node:internal/util/inspect:1881:10)
    at console.value (node:internal/console/constructor:327:14)
    at console.log (node:internal/console/constructor:363:61)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/api/src/controllers/product.controller.js:79:17
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:4892:21
    at _done (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3118:16)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3133:18
    at callbackWrapper (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3087:20)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:4868:18
    at processTicksAndRejections (node:internal/process/task_queues:76:11) {
  errors: {
    averageRating: CastError: Cast to Number failed for value "NaN" (type number) at path "averageRating"
        at SchemaNumber.cast (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/schema/number.js:373:11)
        at SchemaNumber.SchemaType.applySetters (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/schematype.js:1106:12)
        at SchemaNumber.SchemaType.getDefault (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/schematype.js:1052:25)
        at $__applyDefaults (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/document.js:437:24)
        at model.Document (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/document.js:165:5)
        at model.Model (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:105:12)
        at new model (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:4706:15)
        at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3094:22
        at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3130:7
        at Array.forEach (<anonymous>)
        at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3129:15
        at promiseOrCallback (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
        at Mongoose._promiseOrCallback (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/index.js:1149:10)
        at Function.create (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3064:23)
        at exports.createProduct (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/api/src/controllers/product.controller.js:42:11)
        at handleReturn (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/express-promise-router/lib/express-promise-router.js:24:23) {
      stringValue: '"NaN"',
      messageFormat: undefined,
      kind: 'Number',
      value: NaN,
      path: 'averageRating',
      reason: AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
      
        assert.ok(!isNaN(val))
      
          at castNumber (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/cast/number.js:28:10)
          at SchemaNumber.cast (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/schema/number.js:371:12)
          at SchemaNumber.SchemaType.applySetters (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/schematype.js:1106:12)
          at SchemaNumber.SchemaType.getDefault (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/schematype.js:1052:25)
          at $__applyDefaults (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/document.js:437:24)
          at model.Document (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/document.js:165:5)
          at model.Model (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:105:12)
          at new model (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:4706:15)
          at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3094:22
          at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3130:7
          at Array.forEach (<anonymous>)
          at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3129:15
          at promiseOrCallback (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
          at Mongoose._promiseOrCallback (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/index.js:1149:10)
          at Function.create (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3064:23)
          at exports.createProduct (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/api/src/controllers/product.controller.js:42:11) {
        generatedMessage: true,
        code: 'ERR_ASSERTION',
        actual: false,
        expected: true,
        operator: '=='
      },
      valueType: 'number'
    }
  },
  _message: 'Product validation failed'
}
Product.create: undefined
/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:19
            throw error;
            ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:329:5)
    at ServerResponse.setHeader (node:_http_outgoing:579:11)
    at ServerResponse.header (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/express/lib/response.js:158:21)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/api/src/controllers/product.controller.js:85:23
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:4892:21
    at _done (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3118:16)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3133:18
    at callbackWrapper (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:3087:20)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/model.js:4868:18
    at processTicksAndRejections (node:internal/process/task_queues:76:11) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

标签: node.jsmongodbmongoose

解决方案


rating 和 averageRating 都应该是虚拟字段:否则, /0 部门将在您的集合中有一个条目时使您的架构崩溃product.ratings = 0. 所以我要做的是,首先,通过 getter 函数为虚拟字段定义评级:

productSchema.virtual("numberRatings").get(function() {
    return this.ratings.length;
});

假设这this.ratings是一个存储此特定产品的所有评级的数组。这样,每次访问product.numerRatings时,都会显示该数组中更新的条目数量。考虑到这一点,您只需要在averageRating 中添加一点条件逻辑:

productSchema.virtual("averageRating").get(function() {
    return this.ratings.length > 0 ? this.totalRating / this.ratings.length : 0;
});

只要数组中没有评级,product.averageRating就会产生一个 0,而不会尝试任何有问题的除法。数组开始包含评分的那一刻,将计算平均值。


推荐阅读