MongoDB
Beginner
1 min read
Atlas Triggers and Functions
Example
// Atlas Database Trigger — fires on every new order insert
// (Function code, written in the Atlas UI)
exports = async function(changeEvent) {
// changeEvent.fullDocument is the inserted/updated document
const order = changeEvent.fullDocument
// Access another collection via the context
const db = context.services.get("mongodb-atlas").db("shop")
const notifications = db.collection("notifications")
// Insert a notification document
await notifications.insertOne({
userId: order.userId,
message: `Your order #${order._id} has been received.`,
createdAt: new Date(),
read: false
})
// Call an external webhook (e.g. send email via SendGrid)
const response = await context.http.post({
url: "https://api.sendgrid.com/v3/mail/send",
headers: {
"Authorization": [`Bearer ${context.values.get("SENDGRID_KEY")}`],
"Content-Type": ["application/json"]
},
body: JSON.stringify({
to: [{ email: order.customerEmail }],
from: { email: "noreply@myshop.com" },
subject: "Order Confirmed",
content: [{ type: "text/plain", value: `Order ${order._id} confirmed!` }]
})
})
return response.status
}