[英]How to query database with firebase cloud functions
I am trying to query my firestore database using cloud functions. 我正在尝试使用云功能查询我的firestore数据库。 I want to trigger an email notification every time a new reading in my database is under the value of 10. 每当数据库中的新读数低于10时,我都想触发电子邮件通知。
Here is the relevant database structure for reference: database structure . 以下是相关的数据库结构供参考: 数据库结构 。 The "readings" field is an array and each "reading" is a map which holds the fields "date" and "value". “读数”字段是一个数组,每个“读数”都是一个映射,其中包含“日期”和“值”字段。
Currently I am at the point where I can send an email notification every time a new user is created however I want this to work for the database. 目前,我可以在每次创建新用户时发送电子邮件通知,但是我希望此方法适用于数据库。 I am unsure how to query for the "readings" array and then for each individual reading. 我不确定如何查询“读数”数组,然后查询每个单独的读数。
Here is my code so far which sends an email when a new user is created 到目前为止,这是我的代码,当创建新用户时会发送电子邮件
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)); });
See: https://firebase.google.com/docs/firestore/extend-with-functions 请参阅: https : //firebase.google.com/docs/firestore/extend-with-functions
For example, to fire on all new readings added to that first 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
}
});
In further comments you mentioned listening for new readings in all sensor elements, not just your first one. 在进一步的评论中,您提到了在所有传感器元件中监听新的读数,而不仅仅是您的第一个。 This is unfortunately not possible in an efficient / simple way ( source ). 不幸的是,这不可能以有效/简单的方式实现( 来源 )。 Instead you will have to listen to all onUpdate
events on /sensor/
, check if the update is adding a reading, then check the value & send your email. 相反,您将必须侦听/sensor/
上的所有onUpdate
事件,检查更新是否正在添加读数,然后检查值并发送电子邮件。
It may be easier to call the cloud function directly from wherever adds the reading, depending on how many times the /sensor/
path is going to be updated for other reasons (since every time this happens, it's a waste of resources). 直接从任何添加读数的地方调用云函数可能会更容易,这取决于/sensor/
路径由于其他原因而要更新多少次(因为每次发生这种情况都会浪费资源)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.