You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+Firestore中DocumentReference.set()数据无效错误解决求助

解决Firestore DocumentReference.set() 数据格式错误问题

问题根源

  1. Firestore API调用错误:DocumentReference.set() 要求传入单个键值对对象作为数据参数,你当前传入了两个独立值 categoryID 和 name,违反了API要求,这是直接触发报错的原因。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:30:42