I am trying to send data to FireStore form Airtable by using Firestore REST API, and I am stack with sending an array. I get the array as a string in Firestore. But the outcome should be with Housekeeping and Transportation tags as separate items of the array.
const createTagsArr = (arr) => { let r = []; arr.forEach(obj => r.push(obj.name)); return r}
for (let i = 0; i < query.records.length; i++) {
if (query.records[i].getCellValueAsString("approved")) {
let obj = {
"fullDescription": query.records[i].getCellValueAsString("fullDescription"),
"tags": createTagsArr(query.records[i].getCellValue("tags").filter(obj => obj.name)),
"id": query.records[i].getCellValueAsString("initialForm"),
}
arr.push(obj)
}
}
const pushData = async () => {
for (let i = 0; i < arr.length; i++) {
let data = {
fullDescription: { stringValue: arr[i].fullDescription },
tags: { arrayValue: {values: [{stringValue: JSON.stringify(arr[i].tags)}]} },
let response = await fetch(`https://firestore.googleapis.com/v1/projects/{project-name}/databases/(default)/documents/{coolection}/${arr[i].id}?updateMask.fieldPaths=fullDescription&updateMask.fieldPaths=tags`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({ "fields": data })
})
console.log(response)
}
}
const init = async () => {
console.log(providersArr)
await pushData()
}
init()
If I remove JSON.stringify() from this line: tags: { arrayValue: {values: [{stringValue: JSON.stringify(providersArr[i].tags)}]} } I am getting bad request error. I would appreciate any help. Thank you!
Each value of an array must have a key of stringValue
. To be able to separate the values of arr[i].tags
, you should first iterate your arr[i].tags
, construct the object and push it in an array. See sample code below:
const pushData = async () => {
for (let i = 0; i < arr.length; i++) {
// Initiate an empty array.
let tags = [];
// Iterate the `arr[i].tags` to create an array of objects.
for (const tag of arr[i].tags) {
// Construct the object to be pushed in the initialized array.
tags.push({ stringValue: tag });
}
let data = {
fullDescription: { stringValue: arr[i].fullDescription },
// Use the created array here.
tags: { arrayValue: {values: tags} },
}
let response = await fetch(`https://firestore.googleapis.com/v1/projects/{project-name}/databases/(default)/documents/{collection}/${arr[i].id}?updateMask.fieldPaths=fullDescription&updateMask.fieldPaths=tags`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({ "fields": data })
})
console.log(response)
}
}
The code above will result to:
For more information, you may check out these documentation: