如何将 JSON 数据保存到 Google Firebase 的 Firestore 数据库?

Ara*_*vin 7 json node.js firebase node-request google-cloud-firestore

是否可以将 JSON 数据直接保存到 Firebase Firestore?

我尝试保存下面的 json 数据,

数据

[{"id":"1234","name":"Chair","symbol":"CHR"}]
Run Code Online (Sandbox Code Playgroud)

代码:

request({url: 'https://api.example.com/v1/data', json: true}, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            res.send(body);    
            console.log(body);    
        }
        else {
            console.log(response.statusCode + " " + error);
        }
        db.collection('market').doc('price').set(body);

    });
Run Code Online (Sandbox Code Playgroud)

错误

错误:参数“数据”不是有效的文档。Input 不是一个普通的 JavaScript 对象。

解决方法

  1. JSON.parse() 用于正文

    db.collection('market').doc('price').set(JSON.parse(body));
    
    Run Code Online (Sandbox Code Playgroud)
  2. JSON.stringify() 用于正文

    db.collection('market')doc('price').set(JSON.stringify(body));
    
    Run Code Online (Sandbox Code Playgroud)

我仍然收到错误。

Dou*_*son 5

您的 JSON 数据是一个数组。请注意,它被方括号包围:

[{"id":"1234","name":"Chair","symbol":"CHR"}]
Run Code Online (Sandbox Code Playgroud)

您不能将数组用作 Firestore 中文档的内容。也许你只想添加数组的第一个元素,它是一个对象:

db.collection('market').doc('price').set(body[0]);
Run Code Online (Sandbox Code Playgroud)

当然,在对数组进行索引之前,您应该验证该元素是否存在。

  • 这就是我的解决方案。我几乎到处都查看了这个错误,但无法弄清楚为什么会发生这种情况。 (2认同)