Stephen Stilwell
Stephen Stilwell

Reputation: 588

Syntax for writing complex Json to the Cloud Firestore using Cloud Functions?

I have webhook that delivers a JSON payload to my Cloud Function URL. The Cloud Function will take the JSON, and write it to the Cloud Firestore.

I don't know how to handle this case where the complex JSON has brackets [].

My guess is there is some addition syntax I must add for cases like this, where the complex JSON has brackets.

Additionally, for the schema in my cloud firestore, I am trying to take the id from line_items and write it to a Map data type called "line_items" with a single field titled id_line_items.

index.js

const admin = require('firebase-admin');
admin.initializeApp();

exports.webhook = async (req, res) => {
  const payload = req.body;

  await admin.firestore().collection("testCollection1").doc().set({
  
  line_items: {
    id_line_items: payload.line_items.id,
    },
  });
  return res.status(200).end();
}

Json Payload

"line_items": [
        {
            "id": 97,
        }
    ],

I experience no errors when the JSON payload looks like this: Notice how this payload does not have the brackets []

"billing": {
        "id": "97",
    },

Upvotes: 0

Views: 68

Answers (1)

Stephen Stilwell
Stephen Stilwell

Reputation: 588

The Json in question was an array, and I needed to specify the position.

id_line_items: payload.line_items.id,

needs to be changed to:

id_line_items: payload.line_items[0].id,

Upvotes: 1

Related Questions