javascript - 如何使用 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()}
解决方案
推荐阅读
- python - 使用 numpy min、max(或 numba)进行 Python 优化
- android - 两个语句解释
- node.js - 分组后如何对数组值进行排序 - mongodb
- html - TinyMce 编辑器不允许使用 html 标签
- javascript - 无法将表单数据推送到 JSON 文件中
- objective-c - Objective-c 看不到 Swift 类的方法
- r - 合并 R 中的非重复行
- mysql - 如何在 mariadb 的 zabbix 中删除 sysdate -50 分区
- android - 如何知道哪个手指被扫描进行生物识别?
- html - 链接到我的 React 应用程序中的外部 URL