React中如何将useState对象正确插入Firebase Firestore数据库?
解决Firestore插入数据出现嵌套结构的问题
你当前的问题出在addDoc的参数写法上:
你传入的{ price }是ES6对象字面量的简写语法,等价于{ price: price }——这会把你的state对象price再包装一层,最终插入Firestore的就是嵌套结构{ price: { vehicleType: "", price: 0 } }。
要得到预期的扁平结构,直接传入price变量本身即可,不需要额外的对象包裹:
修改前的代码:
const docRef = await addDoc(collection(db, "VehiclePrices"), { price });
修改后的代码:
const docRef = await addDoc(collection(db, "VehiclePrices"), price);
这样插入Firestore的文档结构就会是你期望的{ vehicleType: "", price: 0 }。
内容的提问来源于stack exchange,提问作者Phothong DPS
相关产品推荐
相关产品推荐

