如何通过Firestore Functions将数值正确保存为数字而非字符串?
问题原因
错误出在存储前的转换代码:toFixed()方法的返回值是字符串类型,而非数字类型,所以最终存入数据库的price是字符串。
修复方案
1. 修正存储前的转换逻辑
不要直接使用toFixed()的结果,而是将其转回数字类型,或者用其他方式保留两位小数的数字格式:
// 方式1:先转数字,通过计算保留两位小数(数字类型) const priceNum = Number.parseFloat(price); const floatPrice = isNaN(priceNum) ? 0 : Math.round(priceNum * 100) / 100; // 方式2:将toFixed返回的字符串转回数字 const priceNum = Number.parseFloat(price); const floatPrice = isNaN(priceNum) ? 0 : Number(priceNum.toFixed(2));
2. 前端提前处理(可选但推荐)
即使input的type设为number,e.target.value返回的依然是字符串,建议在前端onChange时就转成数字:
<TextField required size="small" value={price} label="price" type="number" InputLabelProps={{ shrink: true }} onChange={e => setPrice(Number(e.target.value))} />
这样传到后端的price直接是数字类型,减少后端类型转换的风险。
3. 最终存储代码确认
确保存储时传入的是数字类型,修改后存储代码无需变动,但floatPrice已经是数字:
await store.collection("items").doc(id) .set({ title, imageUrl, price: floatPrice, // 此时floatPrice为数字类型 quantity, size, type, });
内容的提问来源于stack exchange,提问作者Kris Swat
相关产品推荐
相关产品推荐

