To use the realtime functionality (liveQuery) on any table/collection, you need to make sure that the following things are true:
where clause during update and delete mutations.Overview tab of the Database section.When you make a live query request to Space Cloud, it first pushes down the initial data in the result set one by one. After that, it just notifies you of any changes that happen to your result set.
Example: Live query to the list of pokemons caught by a trainer:
# Note: Only one single top level field is allowed in subscriptions
subscription {
caught_pokemons(
where: {trainer_id: "1"}
) @mongo {
type
payload {
name
}
find # Object containing the unique fields of the concerned document
}
}const whereClause = cond("trainer_id", "==", "1")
// Callback for data changes:
const onSnapshot = (docs, type, find, doc) => {
// docs is the entire result set maintained by the client SDK
// doc is the concerned doc whereas find is the object containing the unique fields
console.log(docs, type, find, doc)
}
// Callback for error while subscribing
const onError = (err) => {
console.log('Live query error', err)
}
let subscription = db.liveQuery("caught_pokemons")
.where(whereClause).subscribe(onSnapshot, onError)
// Unsubscribe to changes
if (on some logic) {
subscription.unsubscribe()
}
Data pushed down in live query have the following fields:
initial, insert, update, and delete. initial is only applicable when Space Cloud is pushing the initial data down.In case you are interested in only the changes and not the initial values, use can use skipInitial:
subscription {
caught_pokemons @mongo (
where: {trainer_id: $trainerId},
skipInitial: true
){
type
payload {
name
}
find
}
}const whereClause = cond("trainer_id", "==", "1")
// Callback for data changes:
const onSnapshot = (docs, type, find, doc) => {
// docs is the entire result set maintained by the client SDK
// doc is the concerned doc whereas find is the object containing the unique fields
console.log(docs, type, find, doc)
}
// Callback for error while subscribing
const onError = (err) => {
console.log('Live query error', err)
}
let subscription = db.liveQuery("caught_pokemons")
.options({ skipInitial: true })
.where(whereClause).subscribe(onSnapshot, onError)
// Unsubscribe to changes
if (on some logic) {
subscription.unsubscribe()
}