How to save JSON data to Google Firebase's Firestore database?

时间:2018-01-15 18:20:57

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

Is it possible to save JSON data directly to Firebase Firestore?

I tried saving my below json data,

Data

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

Code:

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

    });

Error

Error: Argument "data" is not a valid Document. Input is not a plain JavaScript object.

Workaround

  1. JSON.parse() for the body

    db.collection('market').doc('price').set(JSON.parse(body));
    
  2. JSON.stringify() for the body

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

I am still getting error.

1 个答案:

答案 0 :(得分:1)

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

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

您无法使用数组作为Firestore中文档的内容。也许您只想添加数组的第一个元素,即对象:

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

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