database package Stay organized with collections Save and categorize content based on your preferences.
Firebase Realtime Database
Functions
| Function | Description |
|---|---|
| function(app, ...) | |
| getDatabase(app, url) | Returns the instance of the Realtime Database SDK that is associated with the providedFirebaseApp. Initializes a new instance with default settings if no instance exists or if the existing instance uses a custom database URL. |
| function(db, ...) | |
| connectDatabaseEmulator(db, host, port, options) | Modify the provided instance to communicate with the Realtime Database emulator. Note: This method must be called before performing any other operation. |
| goOffline(db) | Disconnects from the server (all Database operations will be completed offline).The client automatically maintains a persistent connection to the Database server, which will remain active indefinitely and reconnect when disconnected. However, thegoOffline() andgoOnline() methods may be used to control the client connection in cases where a persistent connection is undesirable.While offline, the client will no longer receive data updates from the Database. However, all Database operations performed locally will continue to immediately fire events, allowing your application to continue behaving normally. Additionally, each operation performed locally will automatically be queued and retried upon reconnection to the Database server.To reconnect to the Database and begin receiving remote events, seegoOnline(). |
| goOnline(db) | Reconnects to the server and synchronizes the offline Database state with the server state.This method should be used after disabling the active connection withgoOffline(). Once reconnected, the client will transmit the proper data and fire the appropriate events so that your client "catches up" automatically. |
| ref(db, path) | Returns aReference representing the location in the Database corresponding to the provided path. If no path is provided, theReference will point to the root of the Database. |
| refFromURL(db, url) | Returns aReference representing the location in the Database corresponding to the provided Firebase URL.An exception is thrown if the URL is not a valid Firebase Database URL or it has a different domain than the currentDatabase instance.Note that all query parameters (orderBy,limitToLast, etc.) are ignored and are not applied to the returnedReference. |
| function() | |
| forceLongPolling() | Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. |
| forceWebSockets() | Force the use of websockets instead of longPolling. |
| orderByKey() | Creates a newQueryConstraint that orders by the key.Sorts the results of a query by their (ascending) key values.You can read more aboutorderByKey() inSort data. |
| orderByPriority() | Creates a newQueryConstraint that orders by priority.Applications need not use priority but can order collections by ordinary properties (seeSort data for alternatives to priority. |
| orderByValue() | Creates a newQueryConstraint that orders by value.If the children of a query are all scalar values (string, number, or boolean), you can order the results by their (ascending) values.You can read more aboutorderByValue() inSort data. |
| serverTimestamp() | Returns a placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers. |
| function(delta, ...) | |
| increment(delta) | Returns a placeholder value that can be used to atomically increment the current database value by the provided delta. |
| function(enabled, ...) | |
| enableLogging(enabled, persistent) | Logs debugging information to the console. |
| function(limit, ...) | |
| limitToFirst(limit) | Creates a newQueryConstraint that if limited to the first specific number of children.ThelimitToFirst() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100child_added events. If we have fewer than 100 messages stored in our Database, achild_added event will fire for each message. However, if we have over 100 messages, we will only receive achild_added event for the first 100 ordered messages. As items change, we will receivechild_removed events for each item that drops out of the active list so that the total number stays at 100.You can read more aboutlimitToFirst() inFiltering data. |
| limitToLast(limit) | Creates a newQueryConstraint that is limited to return only the last specified number of children.ThelimitToLast() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100child_added events. If we have fewer than 100 messages stored in our Database, achild_added event will fire for each message. However, if we have over 100 messages, we will only receive achild_added event for the last 100 ordered messages. As items change, we will receivechild_removed events for each item that drops out of the active list so that the total number stays at 100.You can read more aboutlimitToLast() inFiltering data. |
| function(logger, ...) | |
| enableLogging(logger) | Logs debugging information to the console. |
| function(parent, ...) | |
| child(parent, path) | Gets aReference for the location at the specified relative path.The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first"). |
| push(parent, value) | Generates a new child location using a unique key and returns itsReference.This is the most common pattern for adding data to a collection of items.If you provide a value topush(), the value is written to the generated location. If you don't pass a value, nothing is written to the database and the child remains empty (but you can use theReference elsewhere).The unique keys generated bypush() are ordered by the current time, so the resulting list of items is chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).SeeAppend to a list of data. SeeThe 2^120 Ways to Ensure Unique Identifiers. |
| function(path, ...) | |
| orderByChild(path) | Creates a newQueryConstraint that orders by the specified child key.Queries can only order by one key at a time. CallingorderByChild() multiple times on the same query is an error.Firebase queries allow you to order your data by any child key on the fly. However, if you know in advance what your indexes will be, you can define them via the .indexOn rule in your Security Rules for better performance. See thehttps://firebase.google.com/docs/database/security/indexing-data rule for more information.You can read more aboutorderByChild() inSort data. |
| function(query, ...) | |
| get(query) | Gets the most up-to-date result for this query. |
| off(query, eventType, callback) | Detaches a callback previously attached with the correspondingon() (onValue,onChildAdded) listener. Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from the respectiveon callbacks.Detach a callback previously attached withon*(). Callingoff() on a parent listener will not automatically remove listeners registered on child nodes,off() must also be called on any child listeners to remove the callback.If a callback is not specified, all callbacks for the specified eventType will be removed. Similarly, if no eventType is specified, all callbacks for theReference will be removed.Individual listeners can also be removed by invoking their unsubscribe callbacks. |
| onChildAdded(query, callback, cancelCallback) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildAdded(query, callback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildAdded(query, callback, cancelCallback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildChanged(query, callback, cancelCallback) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed event may represent multiple changes to the child. TheDataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildChanged(query, callback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed event may represent multiple changes to the child. TheDataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildChanged(query, callback, cancelCallback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed event may represent multiple changes to the child. TheDataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildMoved(query, callback, cancelCallback) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildMoved(query, callback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildMoved(query, callback, cancelCallback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child. |
| onChildRemoved(query, callback, cancelCallback) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildRemoved event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:- a client explicitly callsremove() on that child or one of its ancestors - a client callsset(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit) |
| onChildRemoved(query, callback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildRemoved event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:- a client explicitly callsremove() on that child or one of its ancestors - a client callsset(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit) |
| onChildRemoved(query, callback, cancelCallback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonChildRemoved event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:- a client explicitly callsremove() on that child or one of its ancestors - a client callsset(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit) |
| onValue(query, callback, cancelCallback) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot passed to the callback will be for the location at whichon() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot (val() will returnnull). |
| onValue(query, callback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot passed to the callback will be for the location at whichon() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot (val() will returnnull). |
| onValue(query, callback, cancelCallback, options) | Listens for data changes at a particular location.This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.AnonValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot passed to the callback will be for the location at whichon() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot (val() will returnnull). |
| query(query, queryConstraints) | Creates a new immutable instance ofQuery that is extended to also include additional query constraints. |
| function(ref, ...) | |
| onDisconnect(ref) | Returns anOnDisconnect object - seeEnabling Offline Capabilities in JavaScript for more information on how to use it. |
| remove(ref) | Removes the data at this Database location.Any data at child locations will also be deleted.The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished. |
| runTransaction(ref, transactionUpdate, options) | Atomically modifies the data at this location.Atomically modify the data at this location. Unlike a normalset(), which just overwrites the data regardless of its previous value,runTransaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.To accomplish this, you passrunTransaction() an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function.Note: Modifying data withset() will cancel any pending transactions at that location, so extreme care should be taken if mixingset() andrunTransaction() to update the same data.Note: When using transactions with Security and Firebase Rules in place, be aware that a client needs.read access in addition to.write access in order to perform a transaction. This is because the client-side nature of transactions requires the client to read the data in order to transactionally update it. |
| set(ref, value) | Writes data to this Database location.This will overwrite any data at this location and all child locations.The effect of the write will be visible immediately, and the corresponding events ("value", "child_added", etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, theonComplete callback will be called asynchronously after synchronization has finished.Passingnull for the new value is equivalent to callingremove(); namely, all data at this location and all child locations will be deleted.set() will remove any priority stored at this location, so if priority is meant to be preserved, you need to usesetWithPriority() instead.Note that modifying data withset() will cancel any pending transactions at that location, so extreme care should be taken if mixingset() andtransaction() to modify the same data.A singleset() will generate a single "value" event at the location where theset() was performed. |
| setPriority(ref, priority) | Sets a priority for the data at this Database location.Applications need not use priority but can order collections by ordinary properties (seeSorting and filtering data ). |
| setWithPriority(ref, value, priority) | Writes data the Database location. Likeset() but also specifies the priority for that data.Applications need not use priority but can order collections by ordinary properties (seeSorting and filtering data ). |
| update(ref, values) | Writes multiple values to the Database at once.Thevalues argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.As opposed to theset() method,update() can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).The effect of the write will be visible immediately, and the corresponding events ('value', 'child_added', etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, theonComplete callback will be called asynchronously after synchronization has finished.A singleupdate() will generate a single "value" event at the location where theupdate() was performed, regardless of how many children were modified.Note that modifying data withupdate() will cancel any pending transactions at that location, so extreme care should be taken if mixingupdate() andtransaction() to modify the same data.Passingnull toupdate() will remove the data at this location.SeeIntroducing multi-location updates and more. |
| function(value, ...) | |
| endAt(value, key) | Creates aQueryConstraint with the specified ending point.UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.The ending point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name less than or equal to the specified key.You can read more aboutendAt() inFiltering data. |
| endBefore(value, key) | Creates aQueryConstraint with the specified ending point (exclusive).UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.The ending point is exclusive. If only a value is provided, children with a value less than the specified value will be included in the query. If a key is specified, then children must have a value less than or equal to the specified value and a key name less than the specified key. |
| equalTo(value, key) | Creates aQueryConstraint that includes children that match the specified value.UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have exactly the specified key as their key name. This can be used to filter result sets with many matches for the same value.You can read more aboutequalTo() inFiltering data. |
| startAfter(value, key) | Creates aQueryConstraint with the specified starting point (exclusive).UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.The starting point is exclusive. If only a value is provided, children with a value greater than the specified value will be included in the query. If a key is specified, then children must have a value greater than or equal to the specified value and a a key name greater than the specified key. |
| startAt(value, key) | Creates aQueryConstraint with the specified starting point.UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.The starting point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name greater than or equal to the specified key.You can read more aboutstartAt() inFiltering data. |
Classes
| Class | Description |
|---|---|
| Database | Class representing a Firebase Realtime Database. |
| DataSnapshot | ADataSnapshot contains data from a Database location.Any time you read data from the Database, you receive the data as aDataSnapshot. ADataSnapshot is passed to the event callbacks you attach withon() oronce(). You can extract the contents of the snapshot as a JavaScript object by calling theval() method. Alternatively, you can traverse into the snapshot by callingchild() to return child snapshots (which you could then callval() on).ADataSnapshot is an efficiently generated, immutable copy of the data at a Database location. It cannot be modified and will never change (to modify data, you always call theset() method on aReference directly). |
| OnDisconnect | TheonDisconnect class allows you to write or clear data when your client disconnects from the Database server. These updates occur whether your client disconnects cleanly or not, so you can rely on them to clean up data even if a connection is dropped or a client crashes.TheonDisconnect class is most commonly used to manage presence in applications where it is useful to detect how many clients are connected and when other clients disconnect. SeeEnabling Offline Capabilities in JavaScript for more information.To avoid problems when a connection is dropped before the requests can be transferred to the Database server, these functions should be called before writing any data.Note thatonDisconnect operations are only triggered once. If you want an operation to occur each time a disconnect occurs, you'll need to re-establish theonDisconnect operations each time you reconnect. |
| QueryConstraint | AQueryConstraint is used to narrow the set of documents returned by a Database query.QueryConstraints are created by invokingendAt(),endBefore(),startAt(),startAfter(),limitToFirst(),limitToLast(),orderByChild(),orderByChild(),orderByKey() ,orderByPriority() ,orderByValue() orequalTo() and can then be passed toquery() to create a new query instance that also contains thisQueryConstraint. |
| TransactionResult | A type for the resolve value ofrunTransaction(). |
Interfaces
| Interface | Description |
|---|---|
| DatabaseReference | ADatabaseReference represents a specific location in your Database and can be used for reading or writing data to that Database location.You can reference the root or child location in your Database by callingref() orref("child/path").Writing is done with theset() method and reading can be done with theon*() method. Seehttps://firebase.google.com/docs/database/web/read-and-write |
| IteratedDataSnapshot | Represents a child snapshot of aReference that is being iterated over. The key will never be undefined. |
| ListenOptions | An options objects that can be used to customize a listener. |
| Query | AQuery sorts and filters the data at a Database location so only a subset of the child data is included. This can be used to order a collection of data by some attribute (for example, height of dinosaurs) as well as to restrict a large list of items (for example, chat messages) down to a number suitable for synchronizing to the client. Queries are created by chaining together one or more of the filter methods defined here.Just as with aDatabaseReference, you can receive data from aQuery by using theon*() methods. You will only receive events andDataSnapshots for the subset of the data that matches your query.Seehttps://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data for more information. |
| ThenableReference | APromise that can also act as aDatabaseReference when returned bypush(). The reference is available immediately and thePromise resolves as the write to the backend completes. |
| TransactionOptions | An options object to configure transactions. |
Type Aliases
| Type Alias | Description |
|---|---|
| EventType | One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved." |
| QueryConstraintType | Describes the different query constraints available in this SDK. |
| Unsubscribe | A callback that can invoked to remove a listener. |
function(app, ...)
getDatabase(app, url)
Returns the instance of the Realtime Database SDK that is associated with the providedFirebaseApp. Initializes a new instance with default settings if no instance exists or if the existing instance uses a custom database URL.
Signature:
exportdeclarefunctiongetDatabase(app?:FirebaseApp,url?:string):Database;Parameters
| Parameter | Type | Description |
|---|---|---|
| app | FirebaseApp | TheFirebaseApp instance that the returned Realtime Database instance is associated with. |
| url | string | The URL of the Realtime Database instance to connect to. If not provided, the SDK connects to the default instance of the Firebase App. |
Returns:
TheDatabase instance of the provided app.
function(db, ...)
connectDatabaseEmulator(db, host, port, options)
Modify the provided instance to communicate with the Realtime Database emulator.
Note: This method must be called before performing any other operation.
Signature:
exportdeclarefunctionconnectDatabaseEmulator(db:Database,host:string,port:number,options?:{mockUserToken?:EmulatorMockTokenOptions|string;}):void;Parameters
| Parameter | Type | Description |
|---|---|---|
| db | Database | The instance to modify. |
| host | string | The emulator host (ex: localhost) |
| port | number | The emulator port (ex: 8080) |
| options | { mockUserToken?:EmulatorMockTokenOptions | string; } |
Returns:
void
goOffline(db)
Disconnects from the server (all Database operations will be completed offline).
The client automatically maintains a persistent connection to the Database server, which will remain active indefinitely and reconnect when disconnected. However, thegoOffline() andgoOnline() methods may be used to control the client connection in cases where a persistent connection is undesirable.
While offline, the client will no longer receive data updates from the Database. However, all Database operations performed locally will continue to immediately fire events, allowing your application to continue behaving normally. Additionally, each operation performed locally will automatically be queued and retried upon reconnection to the Database server.
To reconnect to the Database and begin receiving remote events, seegoOnline().
Signature:
exportdeclarefunctiongoOffline(db:Database):void;Parameters
| Parameter | Type | Description |
|---|---|---|
| db | Database | The instance to disconnect. |
Returns:
void
goOnline(db)
Reconnects to the server and synchronizes the offline Database state with the server state.
This method should be used after disabling the active connection withgoOffline(). Once reconnected, the client will transmit the proper data and fire the appropriate events so that your client "catches up" automatically.
Signature:
exportdeclarefunctiongoOnline(db:Database):void;Parameters
| Parameter | Type | Description |
|---|---|---|
| db | Database | The instance to reconnect. |
Returns:
void
ref(db, path)
Returns aReference representing the location in the Database corresponding to the provided path. If no path is provided, theReference will point to the root of the Database.
Signature:
exportdeclarefunctionref(db:Database,path?:string):DatabaseReference;Parameters
| Parameter | Type | Description |
|---|---|---|
| db | Database | The database instance to obtain a reference for. |
| path | string | Optional path representing the location the returnedReference will point. If not provided, the returnedReference will point to the root of the Database. |
Returns:
If a path is provided, aReference pointing to the provided path. Otherwise, aReference pointing to the root of the Database.
refFromURL(db, url)
Returns aReference representing the location in the Database corresponding to the provided Firebase URL.
An exception is thrown if the URL is not a valid Firebase Database URL or it has a different domain than the currentDatabase instance.
Note that all query parameters (orderBy,limitToLast, etc.) are ignored and are not applied to the returnedReference.
Signature:
exportdeclarefunctionrefFromURL(db:Database,url:string):DatabaseReference;Parameters
| Parameter | Type | Description |
|---|---|---|
| db | Database | The database instance to obtain a reference for. |
| url | string | The Firebase URL at which the returnedReference will point. |
Returns:
AReference pointing to the provided Firebase URL.
function()
forceLongPolling()
Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
Signature:
exportdeclarefunctionforceLongPolling():void;Returns:
void
forceWebSockets()
Force the use of websockets instead of longPolling.
Signature:
exportdeclarefunctionforceWebSockets():void;Returns:
void
orderByKey()
Creates a newQueryConstraint that orders by the key.
Sorts the results of a query by their (ascending) key values.
You can read more aboutorderByKey() inSort data.
Signature:
exportdeclarefunctionorderByKey():QueryConstraint;Returns:
orderByPriority()
Creates a newQueryConstraint that orders by priority.
Applications need not use priority but can order collections by ordinary properties (seeSort data for alternatives to priority.
Signature:
exportdeclarefunctionorderByPriority():QueryConstraint;Returns:
orderByValue()
Creates a newQueryConstraint that orders by value.
If the children of a query are all scalar values (string, number, or boolean), you can order the results by their (ascending) values.
You can read more aboutorderByValue() inSort data.
Signature:
exportdeclarefunctionorderByValue():QueryConstraint;Returns:
serverTimestamp()
Returns a placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers.
Signature:
exportdeclarefunctionserverTimestamp():object;Returns:
object
function(delta, ...)
increment(delta)
Returns a placeholder value that can be used to atomically increment the current database value by the provided delta.
Signature:
exportdeclarefunctionincrement(delta:number):object;Parameters
| Parameter | Type | Description |
|---|---|---|
| delta | number | the amount to modify the current value atomically. |
Returns:
object
A placeholder value for modifying data atomically server-side.
function(enabled, ...)
enableLogging(enabled, persistent)
Logs debugging information to the console.
Signature:
exportdeclarefunctionenableLogging(enabled:boolean,persistent?:boolean):any;Parameters
| Parameter | Type | Description |
|---|---|---|
| enabled | boolean | Enables logging iftrue, disables logging iffalse. |
| persistent | boolean | Remembers the logging state between page refreshes iftrue. |
Returns:
any
function(limit, ...)
limitToFirst(limit)
Creates a newQueryConstraint that if limited to the first specific number of children.
ThelimitToFirst() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100child_added events. If we have fewer than 100 messages stored in our Database, achild_added event will fire for each message. However, if we have over 100 messages, we will only receive achild_added event for the first 100 ordered messages. As items change, we will receivechild_removed events for each item that drops out of the active list so that the total number stays at 100.
You can read more aboutlimitToFirst() inFiltering data.
Signature:
exportdeclarefunctionlimitToFirst(limit:number):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| limit | number | The maximum number of nodes to include in this query. |
Returns:
limitToLast(limit)
Creates a newQueryConstraint that is limited to return only the last specified number of children.
ThelimitToLast() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100child_added events. If we have fewer than 100 messages stored in our Database, achild_added event will fire for each message. However, if we have over 100 messages, we will only receive achild_added event for the last 100 ordered messages. As items change, we will receivechild_removed events for each item that drops out of the active list so that the total number stays at 100.
You can read more aboutlimitToLast() inFiltering data.
Signature:
exportdeclarefunctionlimitToLast(limit:number):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| limit | number | The maximum number of nodes to include in this query. |
Returns:
function(logger, ...)
enableLogging(logger)
Logs debugging information to the console.
Signature:
exportdeclarefunctionenableLogging(logger:(message:string)=>unknown):any;Parameters
| Parameter | Type | Description |
|---|---|---|
| logger | (message: string) => unknown | A custom logger function to control how things get logged. |
Returns:
any
function(parent, ...)
child(parent, path)
Gets aReference for the location at the specified relative path.
The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first").
Signature:
exportdeclarefunctionchild(parent:DatabaseReference,path:string):DatabaseReference;Parameters
| Parameter | Type | Description |
|---|---|---|
| parent | DatabaseReference | The parent location. |
| path | string | A relative path from this location to the desired child location. |
Returns:
The specified child location.
push(parent, value)
Generates a new child location using a unique key and returns itsReference.
This is the most common pattern for adding data to a collection of items.
If you provide a value topush(), the value is written to the generated location. If you don't pass a value, nothing is written to the database and the child remains empty (but you can use theReference elsewhere).
The unique keys generated bypush() are ordered by the current time, so the resulting list of items is chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).
SeeAppend to a list of data. SeeThe 2^120 Ways to Ensure Unique Identifiers.
Signature:
exportdeclarefunctionpush(parent:DatabaseReference,value?:unknown):ThenableReference;Parameters
| Parameter | Type | Description |
|---|---|---|
| parent | DatabaseReference | The parent location. |
| value | unknown | Optional value to be written at the generated location. |
Returns:
CombinedPromise andReference; resolves when write is complete, but can be used immediately as theReference to the child location.
function(path, ...)
orderByChild(path)
Creates a newQueryConstraint that orders by the specified child key.
Queries can only order by one key at a time. CallingorderByChild() multiple times on the same query is an error.
Firebase queries allow you to order your data by any child key on the fly. However, if you know in advance what your indexes will be, you can define them via the .indexOn rule in your Security Rules for better performance. See thehttps://firebase.google.com/docs/database/security/indexing-data rule for more information.
You can read more aboutorderByChild() inSort data.
Signature:
exportdeclarefunctionorderByChild(path:string):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| path | string | The path to order by. |
Returns:
function(query, ...)
get(query)
Gets the most up-to-date result for this query.
Signature:
exportdeclarefunctionget(query:Query):Promise<DataSnapshot>;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
Returns:
Promise<DataSnapshot>
APromise which resolves to the resulting DataSnapshot if a value is available, or rejects if the client is unable to return a value (e.g., if the server is unreachable and there is nothing cached).
off(query, eventType, callback)
Detaches a callback previously attached with the correspondingon*() (onValue,onChildAdded) listener. Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from the respectiveon* callbacks.
Detach a callback previously attached withon*(). Callingoff() on a parent listener will not automatically remove listeners registered on child nodes,off() must also be called on any child listeners to remove the callback.
If a callback is not specified, all callbacks for the specified eventType will be removed. Similarly, if no eventType is specified, all callbacks for theReference will be removed.
Individual listeners can also be removed by invoking their unsubscribe callbacks.
Signature:
exportdeclarefunctionoff(query:Query,eventType?:EventType,callback?:(snapshot:DataSnapshot,previousChildName?:string|null)=>unknown):void;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query that the listener was registered with. |
| eventType | EventType | One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved." If omitted, all callbacks for theReference will be removed. |
| callback | (snapshot:DataSnapshot, previousChildName?: string | null) => unknown | The callback function that was passed toon() orundefined to remove all callbacks. |
Returns:
void
onChildAdded(query, callback, cancelCallback)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildAdded(query:Query,callback:(snapshot:DataSnapshot,previousChildName?:string|null)=>unknown,cancelCallback?:(error:Error)=>unknown):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName?: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
Returns:
A function that can be invoked to remove the listener.
onChildAdded(query, callback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildAdded(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildAdded(query, callback, cancelCallback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildAdded(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,cancelCallback:(error:Error)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildChanged(query, callback, cancelCallback)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed event may represent multiple changes to the child. TheDataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildChanged(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,cancelCallback?:(error:Error)=>unknown):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
Returns:
A function that can be invoked to remove the listener.
onChildChanged(query, callback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed event may represent multiple changes to the child. TheDataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildChanged(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildChanged(query, callback, cancelCallback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed event may represent multiple changes to the child. TheDataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildChanged(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,cancelCallback:(error:Error)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildMoved(query, callback, cancelCallback)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildMoved(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,cancelCallback?:(error:Error)=>unknown):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
Returns:
A function that can be invoked to remove the listener.
onChildMoved(query, callback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildMoved(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildMoved(query, callback, cancelCallback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull if it is the first child.
Signature:
exportdeclarefunctiononChildMoved(query:Query,callback:(snapshot:DataSnapshot,previousChildName:string|null)=>unknown,cancelCallback:(error:Error)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot, previousChildName: string | null) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildRemoved(query, callback, cancelCallback)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildRemoved event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:
- a client explicitly calls
remove()on that child or one of its ancestors - a client callsset(null)on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)
Signature:
exportdeclarefunctiononChildRemoved(query:Query,callback:(snapshot:DataSnapshot)=>unknown,cancelCallback?:(error:Error)=>unknown):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
Returns:
A function that can be invoked to remove the listener.
onChildRemoved(query, callback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildRemoved event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:
- a client explicitly calls
remove()on that child or one of its ancestors - a client callsset(null)on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)
Signature:
exportdeclarefunctiononChildRemoved(query:Query,callback:(snapshot:DataSnapshot)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onChildRemoved(query, callback, cancelCallback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonChildRemoved event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:
- a client explicitly calls
remove()on that child or one of its ancestors - a client callsset(null)on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)
Signature:
exportdeclarefunctiononChildRemoved(query:Query,callback:(snapshot:DataSnapshot)=>unknown,cancelCallback:(error:Error)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, ornull if it is the first child. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onValue(query, callback, cancelCallback)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot passed to the callback will be for the location at whichon() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot (val() will returnnull).
Signature:
exportdeclarefunctiononValue(query:Query,callback:(snapshot:DataSnapshot)=>unknown,cancelCallback?:(error:Error)=>unknown):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
Returns:
A function that can be invoked to remove the listener.
onValue(query, callback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot passed to the callback will be for the location at whichon() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot (val() will returnnull).
Signature:
exportdeclarefunctiononValue(query:Query,callback:(snapshot:DataSnapshot)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
onValue(query, callback, cancelCallback, options)
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. SeeRetrieve Data on the Web for more details.
AnonValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot passed to the callback will be for the location at whichon() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot (val() will returnnull).
Signature:
exportdeclarefunctiononValue(query:Query,callback:(snapshot:DataSnapshot)=>unknown,cancelCallback:(error:Error)=>unknown,options:ListenOptions):Unsubscribe;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The query to run. |
| callback | (snapshot:DataSnapshot) => unknown | A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. |
| cancelCallback | (error: Error) => unknown | An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed anError object indicating why the failure occurred. |
| options | ListenOptions | An object that can be used to configureonlyOnce, which then removes the listener after its first invocation. |
Returns:
A function that can be invoked to remove the listener.
query(query, queryConstraints)
Creates a new immutable instance ofQuery that is extended to also include additional query constraints.
Signature:
exportdeclarefunctionquery(query:Query,...queryConstraints:QueryConstraint[]):Query;Parameters
| Parameter | Type | Description |
|---|---|---|
| query | Query | The Query instance to use as a base for the new constraints. |
| queryConstraints | QueryConstraint[] | The list ofQueryConstraints to apply. |
Returns:
Exceptions
if any of the provided query constraints cannot be combined with the existing or new constraints.
function(ref, ...)
onDisconnect(ref)
Returns anOnDisconnect object - seeEnabling Offline Capabilities in JavaScript for more information on how to use it.
Signature:
exportdeclarefunctiononDisconnect(ref:DatabaseReference):OnDisconnect;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The reference to add OnDisconnect triggers for. |
Returns:
remove(ref)
Removes the data at this Database location.
Any data at child locations will also be deleted.
The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.
Signature:
exportdeclarefunctionremove(ref:DatabaseReference):Promise<void>;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The location to remove. |
Returns:
Promise<void>
Resolves when remove on server is complete.
runTransaction(ref, transactionUpdate, options)
Atomically modifies the data at this location.
Atomically modify the data at this location. Unlike a normalset(), which just overwrites the data regardless of its previous value,runTransaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.
To accomplish this, you passrunTransaction() an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function.
set() will cancel any pending transactions at that location, so extreme care should be taken if mixingset() andrunTransaction() to update the same data.Note: When using transactions with Security and Firebase Rules in place, be aware that a client needs.read access in addition to.write access in order to perform a transaction. This is because the client-side nature of transactions requires the client to read the data in order to transactionally update it.Signature:
exportdeclarefunctionrunTransaction(ref:DatabaseReference,transactionUpdate:(currentData:any)=>unknown,options?:TransactionOptions):Promise<TransactionResult>;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The location to atomically modify. |
| transactionUpdate | (currentData: any) => unknown | A developer-supplied function which will be passed the current data stored at this location (as a JavaScript object). The function should return the new value it would like written (as a JavaScript object). Ifundefined is returned (i.e. you return with no arguments) the transaction will be aborted and the data at this location will not be modified. |
| options | TransactionOptions | An options object to configure transactions. |
Returns:
Promise<TransactionResult>
APromise that can optionally be used instead of theonComplete callback to handle success and failure.
set(ref, value)
Writes data to this Database location.
This will overwrite any data at this location and all child locations.
The effect of the write will be visible immediately, and the corresponding events ("value", "child_added", etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, theonComplete callback will be called asynchronously after synchronization has finished.
Passingnull for the new value is equivalent to callingremove(); namely, all data at this location and all child locations will be deleted.
set() will remove any priority stored at this location, so if priority is meant to be preserved, you need to usesetWithPriority() instead.
Note that modifying data withset() will cancel any pending transactions at that location, so extreme care should be taken if mixingset() andtransaction() to modify the same data.
A singleset() will generate a single "value" event at the location where theset() was performed.
Signature:
exportdeclarefunctionset(ref:DatabaseReference,value:unknown):Promise<void>;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The location to write to. |
| value | unknown | The value to be written (string, number, boolean, object, array, or null). |
Returns:
Promise<void>
Resolves when write to server is complete.
setPriority(ref, priority)
Sets a priority for the data at this Database location.
Applications need not use priority but can order collections by ordinary properties (seeSorting and filtering data ).
Signature:
exportdeclarefunctionsetPriority(ref:DatabaseReference,priority:string|number|null):Promise<void>;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The location to write to. |
| priority | string | number | null | The priority to be written (string, number, or null). |
Returns:
Promise<void>
Resolves when write to server is complete.
setWithPriority(ref, value, priority)
Writes data the Database location. Likeset() but also specifies the priority for that data.
Applications need not use priority but can order collections by ordinary properties (seeSorting and filtering data ).
Signature:
exportdeclarefunctionsetWithPriority(ref:DatabaseReference,value:unknown,priority:string|number|null):Promise<void>;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The location to write to. |
| value | unknown | The value to be written (string, number, boolean, object, array, or null). |
| priority | string | number | null | The priority to be written (string, number, or null). |
Returns:
Promise<void>
Resolves when write to server is complete.
update(ref, values)
Writes multiple values to the Database at once.
Thevalues argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.
As opposed to theset() method,update() can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).
The effect of the write will be visible immediately, and the corresponding events ('value', 'child_added', etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, theonComplete callback will be called asynchronously after synchronization has finished.
A singleupdate() will generate a single "value" event at the location where theupdate() was performed, regardless of how many children were modified.
Note that modifying data withupdate() will cancel any pending transactions at that location, so extreme care should be taken if mixingupdate() andtransaction() to modify the same data.
Passingnull toupdate() will remove the data at this location.
SeeIntroducing multi-location updates and more.
Signature:
exportdeclarefunctionupdate(ref:DatabaseReference,values:object):Promise<void>;Parameters
| Parameter | Type | Description |
|---|---|---|
| ref | DatabaseReference | The location to write to. |
| values | object | Object containing multiple values. |
Returns:
Promise<void>
Resolves when update on server is complete.
function(value, ...)
endAt(value, key)
Creates aQueryConstraint with the specified ending point.
UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.
The ending point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name less than or equal to the specified key.
You can read more aboutendAt() inFiltering data.
Signature:
exportdeclarefunctionendAt(value:number|string|boolean|null,key?:string):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| value | number | string | boolean | null | The value to end at. The argument type depends on whichorderBy() function was used in this query. Specify a value that matches theorderBy() type. When used in combination withorderByKey(), the value must be a string. |
| key | string | The child key to end at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority. |
Returns:
endBefore(value, key)
Creates aQueryConstraint with the specified ending point (exclusive).
UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.
The ending point is exclusive. If only a value is provided, children with a value less than the specified value will be included in the query. If a key is specified, then children must have a value less than or equal to the specified value and a key name less than the specified key.
Signature:
exportdeclarefunctionendBefore(value:number|string|boolean|null,key?:string):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| value | number | string | boolean | null | The value to end before. The argument type depends on whichorderBy() function was used in this query. Specify a value that matches theorderBy() type. When used in combination withorderByKey(), the value must be a string. |
| key | string | The child key to end before, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority. |
Returns:
equalTo(value, key)
Creates aQueryConstraint that includes children that match the specified value.
UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.
The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have exactly the specified key as their key name. This can be used to filter result sets with many matches for the same value.
You can read more aboutequalTo() inFiltering data.
Signature:
exportdeclarefunctionequalTo(value:number|string|boolean|null,key?:string):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| value | number | string | boolean | null | The value to match for. The argument type depends on whichorderBy() function was used in this query. Specify a value that matches theorderBy() type. When used in combination withorderByKey(), the value must be a string. |
| key | string | The child key to start at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority. |
Returns:
startAfter(value, key)
Creates aQueryConstraint with the specified starting point (exclusive).
UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.
The starting point is exclusive. If only a value is provided, children with a value greater than the specified value will be included in the query. If a key is specified, then children must have a value greater than or equal to the specified value and a a key name greater than the specified key.
Signature:
exportdeclarefunctionstartAfter(value:number|string|boolean|null,key?:string):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| value | number | string | boolean | null | The value to start after. The argument type depends on whichorderBy() function was used in this query. Specify a value that matches theorderBy() type. When used in combination withorderByKey(), the value must be a string. |
| key | string | The child key to start after. This argument is only allowed if ordering by child, value, or priority. |
Returns:
startAt(value, key)
Creates aQueryConstraint with the specified starting point.
UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo() allows you to choose arbitrary starting and ending points for your queries.
The starting point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name greater than or equal to the specified key.
You can read more aboutstartAt() inFiltering data.
Signature:
exportdeclarefunctionstartAt(value?:number|string|boolean|null,key?:string):QueryConstraint;Parameters
| Parameter | Type | Description |
|---|---|---|
| value | number | string | boolean | null | The value to start at. The argument type depends on whichorderBy() function was used in this query. Specify a value that matches theorderBy() type. When used in combination withorderByKey(), the value must be a string. |
| key | string | The child key to start at. This argument is only allowed if ordering by child, value, or priority. |
Returns:
EventType
One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."
Signature:
exportdeclaretypeEventType='value'|'child_added'|'child_changed'|'child_moved'|'child_removed';QueryConstraintType
Describes the different query constraints available in this SDK.
Signature:
exportdeclaretypeQueryConstraintType='endAt'|'endBefore'|'startAt'|'startAfter'|'limitToFirst'|'limitToLast'|'orderByChild'|'orderByKey'|'orderByPriority'|'orderByValue'|'equalTo';Unsubscribe
A callback that can invoked to remove a listener.
Signature:
exportdeclaretypeUnsubscribe=()=>void;Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-08-01 UTC.