【问题标题】:How to save JSON data to Google Firebase's Firestore database?如何将 JSON 数据保存到 Google Firebase Firestore 数据库?
【发布时间】:2018-06-24 10:04:36
【问题描述】:

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

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

数据

[{"id":"1234","name":"Chair","symbol":"CHR"}]

代码:

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);

    });

错误

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

解决方法

  1. 正文的 JSON.parse()

    db.collection('market').doc('price').set(JSON.parse(body));
    
  2. 正文的 JSON.stringify()

    db.collection('market')doc('price').set(JSON.stringify(body));
    

我仍然遇到错误。

【问题讨论】:

    标签: json node.js firebase google-cloud-firestore node-request


    【解决方案1】:

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

    [{"id":"1234","name":"Chair","symbol":"CHR"}]
    

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

    db.collection('market').doc('price').set(body[0]);
    

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

    【讨论】:

    • 这是我的解决方案。我几乎到处都查看过这个错误,但无法弄清楚它发生的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2019-12-24
    • 2018-07-21
    相关资源
    最近更新 更多