Node.js+Firestore中DocumentReference.set()数据无效错误解决求助
解决Firestore DocumentReference.set() 数据格式错误问题
问题根源
- Firestore API调用错误:
DocumentReference.set()要求传入单个键值对对象作为数据参数,你当前传入了两个独立值categoryID和name,违反了API要求,这是直接触发报错的原因。 - Model类语法错误:
- 拼写错误:
firefose应为mongoose(若使用MongoDB),但Firestore无需Schema定义,该写法混淆了不同数据库的语法。 - 构造函数中未正确给实例属性赋值,直接对参数
categoryID赋值不会绑定到实例对象。
- 拼写错误:
修复方案
1. 修正Controller中的Firestore调用
将set()的参数改为包含字段的对象:
const addProduct = async (req, res, next) => { try { const { categoryID, name } = req.body; // 传入键值对对象,符合Firestore set()方法要求 await firestore.collection('product').doc().set({ categoryID, name }); res.send('产品保存成功'); } catch (error) { res.status(400).send(error.message); } }
2. 修正Product Model类
因使用Firestore,Model只需简单定义数据结构,无需Mongoose Schema语法:
class Product { constructor(id, name, categoryID) { this.id = id; this.categoryID = categoryID; // 正确绑定到实例属性 this.name = name; } } module.exports = Product;
额外说明
- 确保
categoryID是Firestore中category集合下已存在文档的有效ID字符串,后续可通过该ID实现跨集合关联查询。 - 若你实际使用的是MongoDB+Mongoose,需重新调整逻辑:定义正确的Schema并使用Mongoose的
create()方法,而非Firestore API。
内容的提问来源于stack exchange,提问作者Dasun Dola
相关产品推荐
相关产品推荐

