通过 Cloud Firestore REST 添加数组 API

Add array via Cloud Firestore REST API

我正在尝试使用 Firestore REST API 将数据从 Airtable 发送到 FireStore,并且我正在发送一个数组。我在 Firestore 中将数组作为字符串获取。但结果应该是 Housekeeping 和 Transportation 标签作为数组的单独项目。

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

如果我从这一行中删除 JSON.stringify() : 标签:{ arrayValue: {values: [{stringValue: JSON.stringify(providersArr[i].tags)}]} } 我收到错误的请求错误。 我将不胜感激任何帮助。谢谢!

数组的每个值都必须有一个键stringValue。为了能够分离 arr[i].tags 的值,您应该首先迭代 arr[i].tags,构造对象并将其放入数组中。请参阅下面的示例代码:

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

上面的代码将导致:


有关更多信息,您可以查看这些文档: