我正在尝试使用云函数查询我的 firestore 数据库。 每次我的数据库中的新读数低于 10 时,我都想触发电子邮件通知。
这里是相关的数据库结构供引用:database structure . “读数”字段是一个数组,每个“读数”是一个包含字段“日期”和“值”的映射。
目前,我可以在每次创建新用户时发送电子邮件通知,但我希望这适用于数据库。我不确定如何查询“读数”数组,然后再查询每个读数。
到目前为止,这是我的代码,它会在创建新用户时发送电子邮件
exports.sendNotification = functions.auth.user().onCreate((user) => { const mailOptions = { from: '"Spammy Corp." <noreply@firebase.com>', to:"fakeEmail@btopenworld.com", text: "TEST" }; return mailTransport.sendMail(mailOptions) .then(() => console.log("It worked")) .catch((error) => console.error('There was an error while sending the email:', error)); });
最佳答案
参见:https://firebase.google.com/docs/firestore/extend-with-functions
例如,触发添加到第一个 child 的所有新读数:
exports.sendEmail = functions.firestore
.document('sensor/UGt.../readings')
.onCreate((snap, context) => {
const newValue = snap.data();
const value = newValue.value;
if (value < 10) {
// send email
}
});
在进一步的评论中,您提到了监听所有 传感器元件的新读数,而不仅仅是您的第一个。不幸的是,这不可能以高效/简单的方式 ( source )。相反,您必须监听 /sensor/
上的所有 onUpdate
事件,检查更新是否正在添加读数,然后检查值并发送您的电子邮件。
直接从添加读数的地方调用云函数可能更容易,这取决于 /sensor/
路径因其他原因将被更新多少次(因为每次发生这种情况,这是一种资源浪费)。
关于javascript - 如何使用 firebase 云函数查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638038/