Properties

key

(string or null)

The last part of the Reference's path.

For example, "ada" is the key for https://<DATABASE_NAME>.firebaseio.com/users/ada.

The key of a root Reference is null.

Examples

// The key of a root reference is null
var rootRef = firebase.database().ref();
var key = rootRef.key;  // key === null
// The key of any non-root reference is the last token in the path
var adaRef = firebase.database().ref("users/ada");
var key = adaRef.key;  // key === "ada"
key = adaRef.child("name/last").key;  // key === "last"

parent

nullable firebase.database.Reference

The parent location of a Reference.

The parent of a root Reference is null.

Examples

// The parent of a root reference is null
var rootRef = firebase.database().ref();
parent = rootRef.parent;  // parent === null
// The parent of any non-root reference is the parent location
var usersRef = firebase.database().ref("users");
var adaRef = firebase.database().ref("users/ada");
// usersRef and adaRef.parent represent the same location

ref

unknown

Returns a Reference to the Query's location.

Inherited from
firebase.database.Query#ref

root

non-null firebase.database.Reference

The root Reference of the Database.

Examples

// The root of a root reference is itself
var rootRef = firebase.database().ref();
// rootRef and rootRef.root represent the same location
// The root of any non-root reference is the root location
var adaRef = firebase.database().ref("users/ada");
// rootRef and adaRef.root represent the same location

Methods

child

child(path) returns firebase.database.Reference

Gets a Reference 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").

Parameter

path

string

A relative path from this location to the desired child location.

Returns

non-null firebase.database.Reference The specified child location.

Example

var usersRef = firebase.database().ref('users');
var adaRef = usersRef.child('ada');
var adaFirstNameRef = adaRef.child('name/first');
var path = adaFirstNameRef.toString();
// path is now 'https://sample-app.firebaseio.com/users/ada/name/first'

endAt

endAt(value, key) returns firebase.database.Query

Creates a Query with the specified ending point.

Using startAt(), endAt(), and equalTo() 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 about endAt() in Filtering data.

Parameter

value

The value to end at. The argument type depends on which orderBy*() function was used in this query. Specify a value that matches the orderBy*() type. When used in combination with orderByKey(), the value must be a string.

key

Optional

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
Inherited from
firebase.database.Query#endAt

Example

// Find all dinosaurs whose names come before Pterodactyl lexicographically.
var ref = firebase.database().ref("dinosaurs");
ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
  console.log(snapshot.key);
});

equalTo

equalTo(value, key) returns firebase.database.Query

Creates a Query that includes children that match the specified value.

Using startAt(), endAt(), and equalTo() allows us to choose arbitrary starting and ending points for our 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 about equalTo() in Filtering data.

Parameter

value

The value to match for. The argument type depends on which orderBy*() function was used in this query. Specify a value that matches the orderBy*() type. When used in combination with orderByKey(), the value must be a string.

key

Optional

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
Inherited from
firebase.database.Query#equalTo

Example

// Find all dinosaurs whose height is exactly 25 meters.
var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
  console.log(snapshot.key);
});

isEqual

isEqual(other) returns boolean

Returns whether or not the current and provided queries represent the same location, have the same query parameters, and are from the same instance of firebase.app.App.

Two Reference objects are equivalent if they represent the same location and are from the same instance of firebase.app.App.

Two Query objects are equivalent if they represent the same location, have the same query parameters, and are from the same instance of firebase.app.App. Equivalent queries share the same sort order, limits, and starting and ending points.

Parameter

other

The query to compare against.

Returns

Whether or not the current and provided queries are equivalent.

Inherited from
firebase.database.Query#isEqual

Examples

var rootRef = firebase.database.ref();
var usersRef = rootRef.child("users");

usersRef.isEqual(rootRef);  // false
usersRef.isEqual(rootRef.child("users"));  // true
usersRef.parent.isEqual(rootRef);  // true
var rootRef = firebase.database.ref();
var usersRef = rootRef.child("users");
var usersQuery = usersRef.limitToLast(10);

usersQuery.isEqual(usersRef);  // false
usersQuery.isEqual(usersRef.limitToLast(10));  // true
usersQuery.isEqual(rootRef.limitToLast(10));  // false
usersQuery.isEqual(usersRef.orderByKey().limitToLast(10));  // false

limitToFirst

limitToFirst(limit) returns firebase.database.Query

Generates a new Query limited to the first specific number of children.

The limitToFirst() 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 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message. However, if we have over 100 messages, we will only receive a child_added event for the first 100 ordered messages. As items change, we will receive child_removed events for each item that drops out of the active list so that the total number stays at 100.

You can read more about limitToFirst() in Filtering data.

Parameter

limit

The maximum number of nodes to include in this query.

Returns
Inherited from
firebase.database.Query#limitToFirst

Example

// Find the two shortest dinosaurs.
var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").limitToFirst(2).on("child_added", function(snapshot) {
  // This will be called exactly two times (unless there are less than two
  // dinosaurs in the Database).

  // It will also get fired again if one of the first two dinosaurs is
  // removed from the data set, as a new dinosaur will now be the second
  // shortest.
  console.log(snapshot.key);
});

limitToLast

limitToLast(limit) returns firebase.database.Query

Generates a new Query object limited to the last specific number of children.

The limitToLast() 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 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message. However, if we have over 100 messages, we will only receive a child_added event for the last 100 ordered messages. As items change, we will receive child_removed events for each item that drops out of the active list so that the total number stays at 100.

You can read more about limitToLast() in Filtering data.

Parameter

limit

The maximum number of nodes to include in this query.

Returns
Inherited from
firebase.database.Query#limitToLast

Example

// Find the two heaviest dinosaurs.
var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("weight").limitToLast(2).on("child_added", function(snapshot) {
  // This callback will be triggered exactly two times, unless there are
  // fewer than two dinosaurs stored in the Database. It will also get fired
  // for every new, heavier dinosaur that gets added to the data set.
  console.log(snapshot.key);
});

off

off(eventType, callback, context)

Detaches a callback previously attached with on().

Detach a callback previously attached with on(). Note that if on() was called multiple times with the same eventType and callback, the callback will be called multiple times for each event, and off() must be called multiple times to remove the callback. Calling off() 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 or callback is specified, all callbacks for the Reference will be removed.

Parameter

eventType

Optional

One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."

callback

Optional

The callback function that was passed to on().

context

Optional

The context that was passed to on().

Inherited from
firebase.database.Query#off

Examples

var onValueChange = function(dataSnapshot) {  ... };
ref.on('value', onValueChange);
ref.child('meta-data').on('child_added', onChildAdded);
// Sometime later...
ref.off('value', onValueChange);

// You must also call off() for any child listeners on ref
// to cancel those callbacks
ref.child('meta-data').off('child_added', onValueAdded);
// Or you can save a line of code by using an inline function
// and on()'s return value.
var onValueChange = ref.on('value', function(dataSnapshot) { ... });
// Sometime later...
ref.off('value', onValueChange);

on

on(eventType, callback, cancelCallbackOrContext, context) returns function()

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. Use off( ) to stop receiving updates. See Retrieve Data on the Web for more details.

value event

This event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() 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 empty DataSnapshot ( val() will return null).

child_added event

This 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. The DataSnapshot 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, or null if it is the first child.

child_removed event

This event will be triggered once every time a child is removed. The DataSnapshot 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 calls set(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)

child_changed event

This event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot 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, or null if it is the first child.

child_moved event

This event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot 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, or null if it is the first child.

Parameter

eventType

One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."

callback

A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child.

Value must not be null.

cancelCallbackOrContext

Optional

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 an Error object indicating why the failure occurred.

context

Optional

If provided, this object will be used as this when calling your callback(s).

Returns

The provided callback function is returned unmodified. This is just for convenience if you want to pass an inline function to on() but store the callback function for later passing to off().

Inherited from
firebase.database.Query#on

Examples

Handle a new value:

ref.on('value', function(dataSnapshot) {
  ...
});

Handle a new child:

ref.on('child_added', function(childSnapshot, prevChildKey) {
  ...
});

Handle child removal:

ref.on('child_removed', function(oldChildSnapshot) {
  ...
});

Handle child data changes:

ref.on('child_changed', function(childSnapshot, prevChildKey) {
  ...
});

Handle child ordering changes:

ref.on('child_moved', function(childSnapshot, prevChildKey) {
  ...
});

once

once(eventType, successCallback, failureCallbackOrContext, context) returns firebase.Promise containing any type

Listens for exactly one event of the specified event type, and then stops listening.

This is equivalent to calling on(), and then calling off() inside the callback function. See on() for details on the event types.

Parameter

eventType

One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."

successCallback

Optional

A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child by sort order, or null if it is the first child.

failureCallbackOrContext

Optional

An optional callback that will be notified if your client does not have permission to read the data. This callback will be passed an Error object indicating why the failure occurred.

context

Optional

If provided, this object will be used as this when calling your callback(s).

Returns
Inherited from
firebase.database.Query#once

Example

// Basic usage of .once() to read the data located at ref.
ref.once('value')
  .then(function(dataSnapshot) {
    // handle read data.
  });

onDisconnect

onDisconnect() returns firebase.database.OnDisconnect

Returns an OnDisconnect object - see Enabling Offline Capabilities in JavaScript for more information on how to use it.

Returns

non-null firebase.database.OnDisconnect 

orderByChild

orderByChild(path) returns firebase.database.Query

Generates a new Query object ordered by the specified child key.

Queries can only order by one key at a time. Calling orderByChild() 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 the .indexOn rule for more information.

You can read more about orderByChild() in Sort data.

Parameter

path

Returns
Inherited from
firebase.database.Query#orderByChild

Example

var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").on("child_added", function(snapshot) {
  console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
});

orderByKey

orderByKey() returns firebase.database.Query

Generates a new Query object ordered by key.

Sorts the results of a query by their (ascending) key values.

You can read more about orderByKey() in Sort data.

Returns
Inherited from
firebase.database.Query#orderByKey

Example

var ref = firebase.database().ref("dinosaurs");
ref.orderByKey().on("child_added", function(snapshot) {
  console.log(snapshot.key);
});

orderByPriority

orderByPriority() returns firebase.database.Query

Generates a new Query object ordered by priority.

Applications need not use priority but can order collections by ordinary properties (see Sort data for alternatives to priority.

Returns
Inherited from
firebase.database.Query#orderByPriority

orderByValue

orderByValue() returns firebase.database.Query

Generates a new Query object ordered 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 about orderByValue() in Sort data.

Returns
Inherited from
firebase.database.Query#orderByValue

Example

var scoresRef = firebase.database().ref("scores");
scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
  snapshot.forEach(function(data) {
    console.log("The " + data.key + " score is " + data.val());
  });
});

push

push(value, onComplete) returns firebase.database.ThenableReference

Generates a new child location using a unique key and returns its Reference.

This is the most common pattern for adding data to a collection of items.

If you provide a value to push(), the value will be written to the generated location. If you don't pass a value, nothing will be written to the Database and the child will remain empty (but you can use the Reference elsewhere).

The unique key generated by push() are ordered by the current time, so the resulting list of items will be chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).

See Append to a list of data
See The 2^120 Ways to Ensure Unique Identifiers

Parameter

value

Optional

any type

Optional value to be written at the generated location.

onComplete

Optional

function(nullable Error)

Callback called when write to server is complete.

Returns

non-null firebase.database.ThenableReference Combined Promise and Reference; resolves when write is complete, but can be used immediately as the Reference to the child location.

Example

var messageListRef = firebase.database().ref('message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({
  'user_id': 'ada',
  '