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

1

10

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.

Windywindzer answered 15/1, 2018 at 18:20 Comment(0)
A
6

Your JSON data is an array. Notice that it's surrounded with square brackets:

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

You can't use an array as the contents of a document in Firestore. Perhaps you just want to add the first element of the array, which is an object:

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

Of course, before indexing into an array, you should verify that the element exists.

Alleris answered 15/1, 2018 at 19:17 Comment(1)
This was the solution for me. I looked pretty much everywhere about this error and could not figure out why it was happening.Sienese

© 2022 - 2024 — McMap. All rights reserved.