Skip to main content

Real-time push

CloudBase database supports listening for update events of data that matches the query criteria in collections.

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.

// 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);
}
});

Closing the Listener

Call watcher.close() to close the listener.