首页 > 解决方案 > 如何使用 nodejs 在数组中追加对象?

问题描述

我正在尝试将 req.body 推入一个数组并将它们添加到 firestore 中,当我这样做时,我无法在数组中一个接一个地附加响应,而是被最新的 req.body 覆盖,在这里是我尝试过的方法。

app.post("/webhook", async (req, res) => {
try{
    const phoneNumber = req.body.data.source;
    console.log(req.body.data.source);
    const profileSnapshot = await db
      .collection("Profiles")
      .where("phoneNumber", "==", `${phoneNumber}`)
      .get();
      if (profileSnapshot.docs.length === 1) {console.log('known)}
      else{
           console.log("unknown");
      const converstations = [];
      const outbound = [];
      if (
        req.body.data.content.text === "Hi" ||
        req.body.data.content.text === "hi"
      ) {
        converstations.push(JSON.stringify(req.body));

      

      }
      if (req.body.data.content.text === "1") {
        converstations.push(JSON.stringify(req.body));

        console.log("sending a link to the website for signup");
      } else if (req.body.data.content.text === "2") {
        converstations.push(JSON.stringify(req.body));

        console.log(
          "Add contact /upload"
        );
      }
      await db
        .collection("WhatsappConversations")
        .doc(getISO8601Date())
        .collection("Conversations")
        .doc(phoneNumber)
        .set(
          {
            conversation: converstations,
            timestamp: Date.now(),
          },
          { merge: true }
        );
      }
} catch (error) {
    console.error(error);
  }
})

我希望数据以这种格式存储

{
conversations:[{},{},{}],
timestamp:Date.now()}

标签: javascriptnode.jsgoogle-cloud-firestoregoogle-cloud-functions

解决方案


推荐阅读