node.js - 在计算字段 Mongoose 上的路径中,值“NaN”(类型编号)转换为数字失败
问题描述
在我的架构中,我添加了 3 个非必需参数ratings
,totalRating
用于自动计算averageRating
。更新现有记录时,一切顺利,但单参数记录创建失败,出现Product.create error: Error: Product validation failed: averageRating: Cast to Number failed for value "NaN" (type number) at path "averageRating"
. 我尝试在请求正文中添加ratings
andtotalRating
并将其默认设置为 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'
}
解决方案
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,而不会尝试任何有问题的除法。数组开始包含评分的那一刻,将计算平均值。
推荐阅读
- chef-infra - 在厨师食谱中编写循环的最佳实践是什么?
- python - Kivy 文字转语音
- azure-active-directory - 使用 C# 为 SPFX SSO Azure AD 生成访问令牌而不提示用户(自动)
- bash - 在 ubuntu 终端或 bash 脚本中使用系统参数运行 Matlab 脚本
- python - 将函数传递给多处理池中的地图或星图
- html - SCSS 文件在 index.html 实时服务器上不起作用
- maven - 无法使用 authentication=ActiveDirectoryPassword 通过 JDBC 连接到 Azure Synapse DB
- python - 如何使用断言方法比较python unittest中的2个数据帧
- blockchain - 验证由 web3 中的 eth.personal.sign() 签署的智能合约中的签名问题
- python - 如何编辑来自另一个命令的嵌入?(discord.py)