我具有Firebase Firestore的此功能,每次在集合pagos
中创建新文档时,我都会通过Sendgrid发送包含创建的新文档数据的交易电子邮件。效果很好。
我的问题是我该如何执行相同的功能,即发送所述电子邮件,但仅当文档使用特定字段(例如dataPago
)更新时才能完成?
在创建文档时,这是我的功能:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const SENDGRID_API_KEY = functions.config().sendgrid.key
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
exports.pagoRealizado = functions.firestore
.document('pagos/{pagoId}')
.onCreate((snap, context) => {
const pagoId = context.params.pagoId;
const db = admin.firestore()
return db.collection('pagos').doc(pagoId)
.get()
.then(doc => {
const pago = doc.data();
const msg = {
from: 'xxx@gmail.com',
to: 'xxx@xxx.com',
templateId: 'd-3473a9cc588245b7b2a6633f05dafdd8',
substitutionWrappers: ['{{', '}}'],
dynamic_template_data: {
nombre: pago.dataCliente.nombre,
}
};
return sgMail.send(msg)
})
.then(() => console.log('email enviado!'))
.catch(err => console.log(err))
});
答案 0 :(得分:1)
可以使用onUpdate触发器代替使用onCreate触发器。只要以某种方式更改但未创建或删除匹配的文档,就会触发该事件。您可以在documentation中详细了解每种Firestore触发器。
您无法在文档中的特定字段上设置触发器。当文档中的任何字段以任何方式更改时,触发器将触发。您必须检查传递给该函数的文档快照的前后状态,以便确定是否要执行此更改。再次,文档详细讨论了这一点。