Real-time push
CloudBase database supports listening for update events of data that matches the query criteria in collections.
PostgreSQL table changes, Broadcast, and Presence
Keep using watch() on this page for document-database collections. For Broadcast / Presence / PostgreSQL CDC, use JS SDK app.realtime().
Setting Up a Listener
Use the watch() method to set up a listener, which returns a watcher object for closing the listener.
Any change in the documents that meet the conditions will trigger the onChange callback.
- Mini Program
- Web
// 1. Get the database reference
const db = wx.cloud.database();
const watcher = db
.collection("todos")
.where({
// query...
})
.watch({
onChange: function(snapshot) {
console.log("snapshot", snapshot);
},
onError: function(err) {
console.error("the watch closed because of error", err);
}
});
const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({
env: "xxxx"
});
// 1. Get the database reference
var db = app.database();
const watcher = db
.collection("todos")
.where({
// query...
})
.watch({
onChange: function(snapshot) {
console.log("snapshot", snapshot);
},
onError: function(err) {
console.error("the watch closed because of error", err);
}
});
Closing the Listener
Call watcher.close() to close the listener.