next.js 使用admin sdk和Firebase云函数从Firestore检索对象数组

6jygbczu  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(151)

我正在使用Firebase开发Next JS应用程序,我一直在研究Firebase Cloud功能以及如何在onCreate或onUpdate触发器后检索数据。我是管理SDK的新手,所以请原谅我的问题看起来很简单。
我的文档结构如下所示:

{
  "amount" : 123, 
  "code" : "RAB45MGTRK",
  "createdOn" : "Wed Jan 11 2023 08:34:25 GMT+0000 (Coordinated Universal Time)",
  "phone" : "0700 000 000", 
  "rice" : "160",
  "sugar" : "136",
  "user_id" : "IjsdigsdTr345499",
  "items" : [
    {
      "product" : "productOne", 
      "quantity" : "2"
    },
        {
      "product" : "productTwo", 
      "quantity" : "3"
    }
  ]
}

我检索数据如下:

exports.productPurchased = functions.firestore
    .document('purchases/{productPurchaseId}')
    .onCreate((doc, context) => {
      const documentId = context.params.productPurchaseId;
      const purchaseData = doc.data();

       const purchase = {
        amount: `${purchaseData.amount}`,
        uid: `${purchaseData.user_id}`,
        phoneNumber: `${purchaseData.phone}`, 
        items: `${purchaseData.items}`, //this is where I have the issue
        docId: documentId,
        createdOn: admin.firestore.FieldValue.serverTimestamp()
    }

    return productPurchase(purchase)
  })

其他的字段都被检索到了好的,挑战在于数组。我想得到对象数组和,并将它们插入到purchase对象中,这样它们就变成了:

"productOne" : "2", 
"productTwo" : "3"

有人知道怎么做吗?

hiz5n14c

hiz5n14c1#

删除反勾号以获取数组

exports.productPurchased = functions.firestore
    .document('purchases/{productPurchaseId}')
    .onCreate((doc, context) => {
      const documentId = context.params.productPurchaseId;
      const purchaseData = doc.data();

       const purchase = {
        amount: `${purchaseData.amount}`,
        uid: `${purchaseData.user_id}`,
        phoneNumber: `${purchaseData.phone}`, 
        items: purchaseData.items, //this is where I have the issue
        docId: documentId,
        createdOn: admin.firestore.FieldValue.serverTimestamp()
    }

    return productPurchase(purchase)
  })

并在productPurchase函数中接收对象:

const productPurchase = (data => {
    const newData = data;
    const pArray = Object.entries(data.items);

    pArray.forEach(([key, val]) => {
        newData[val.product] = val.quantity;
    })

    //do what you want with newData
})

相关问题