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 attachwithon() oronce(). You can extract the contents of the snapshot as aJavaScript object by calling theval() method. Alternatively, you cantraverse 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 ata Database location. It cannot be modified and will never change (to modifydata, you always call theset() method on aReference directly).
Index
Properties
key
The key (last part of the path) of the location of thisDataSnapshot.
The last token in a Database location is considered its key. For example,"ada" is the key for the /users/ada/ node. Accessing the key on anyDataSnapshot will return the key for the location that generated it.However, accessing the key on the root URL of a Database will returnnull.
- example
// Assume we have the following data in the Database:{"name": {"first":"Ada","last":"Lovelace" }}var ref = firebase.database().ref("users/ada");ref.once("value") .then(function(snapshot){var key = snapshot.key;// "ada"var childKey = snapshot.child("name/last").key;// "last" });- example
var rootRef = firebase.database().ref();rootRef.once("value") .then(function(snapshot){var key = snapshot.key;// nullvar childKey = snapshot.child("users/ada").key;// "ada" });
ref
TheReference for the location that generated thisDataSnapshot.
Methods
child
- child(path: string):DataSnapshot
Gets another
DataSnapshotfor the location at the specified relative path.Passing a relative path to the
child()method of a DataSnapshot returnsanotherDataSnapshotfor the location at the specified relative path. Therelative path can either be a simple child name (for example, "ada") or adeeper, slash-separated path (for example, "ada/name/first"). If the childlocation has no data, an emptyDataSnapshot(that is, aDataSnapshotwhose value isnull) is returned.- example
// Assume we have the following data in the Database:{"name": {"first":"Ada","last":"Lovelace" }}// Test for the existence of certain keys within a DataSnapshotvar ref = firebase.database().ref("users/ada");ref.once("value") .then(function(snapshot){var name = snapshot.child("name").val();// {first:"Ada",last:"Lovelace"}var firstName = snapshot.child("name/first").val();// "Ada"var lastName = snapshot.child("name").child("last").val();// "Lovelace"var age = snapshot.child("age").val();// null });
Parameters
path:string
A relative path to the location of child data.
ReturnsDataSnapshot
exists
- exists():boolean
Returns true if this
DataSnapshotcontains any data. It is slightly moreefficient than usingsnapshot.val() !== null.- example
// Assume we have the following data in the Database:{"name": {"first":"Ada","last":"Lovelace" }}// Test for the existence of certain keys within a DataSnapshotvar ref = firebase.database().ref("users/ada");ref.once("value") .then(function(snapshot){var a = snapshot.exists();// truevar b = snapshot.child("name").exists();// truevar c = snapshot.child("name/first").exists();// truevar d = snapshot.child("name/middle").exists();// false });
Returnsboolean
exportVal
- export
Val():any Exports the entire contents of the DataSnapshot as a JavaScript object.
The
exportVal()method is similar toval(), except priority informationis included (if available), making it suitable for backing up your data.Returnsany
The DataSnapshot's contents as a JavaScript value (Object,Array, string, number, boolean, or
null).
forEach
- for
Each(action: (a: IteratedDataSnapshot) =>boolean |void):boolean Enumerates the top-level children in the
DataSnapshot.Because of the way JavaScript objects work, the ordering of data in theJavaScript object returned by
val()is not guaranteed to match the orderingon the server nor the ordering ofchild_addedevents. That is whereforEach()comes in handy. It guarantees the children of aDataSnapshotwill be iterated in their query order.If no explicit
orderBy*()method is used, results are returnedordered by key (unless priorities are used, in which case, results arereturned by priority).- example
// Assume we have the following data in the Database:{"users": {"ada": {"first":"Ada","last":"Lovelace" },"alan": {"first":"Alan","last":"Turing" } }}// Loop through users in order with the forEach() method. The callback// provided to forEach() will be called synchronously with a DataSnapshot// for each child:var query = firebase.database().ref("users").orderByKey();query.once("value") .then(function(snapshot){ snapshot.forEach(function(childSnapshot){// key will be "ada" the first time and "alan" the second timevar key = childSnapshot.key;// childData will be the actual contents of the childvar childData = childSnapshot.val(); });});- example
// You can cancel the enumeration at any point by having your callback// function return true. For example, the following code sample will only// fire the callback function one time:var query = firebase.database().ref("users").orderByKey();query.once("value") .then(function(snapshot){ snapshot.forEach(function(childSnapshot){var key = childSnapshot.key;// "ada"// Cancel enumerationreturntrue; });});
Parameters
action:(a:IteratedDataSnapshot) =>boolean |void
A functionthat will be called for each child DataSnapshot. The callback can returntrue to cancel further enumeration.
- (a:IteratedDataSnapshot):boolean |void
Parameters
Returnsboolean |void
Returnsboolean
true if enumeration was canceled due to your callbackreturning true.
getPriority
- get
Priority():string |number |null Gets the priority value of the data in this
DataSnapshot.Applications need not use priority but can order collections byordinary properties (see Sorting and filtering data).
Returnsstring |number |null
hasChild
- has
Child(path: string):boolean Returns true if the specified child path has (non-null) data.
- example
// Assume we have the following data in the Database:{"name": {"first":"Ada","last":"Lovelace" }}// Determine which child keys in DataSnapshot have data.var ref = firebase.database().ref("users/ada");ref.once("value") .then(function(snapshot){var hasName = snapshot.hasChild("name");// truevar hasAge = snapshot.hasChild("age");// false });
Parameters
path:string
A relative path to the location of a potential child.
Returnsboolean
trueif data exists at the specified child path; elsefalse.
hasChildren
- has
Children():boolean Returns whether or not the
DataSnapshothas any non-nullchildproperties.You can use
hasChildren()to determine if aDataSnapshothas anychildren. If it does, you can enumerate them usingforEach(). If itdoesn't, then either this snapshot contains a primitive value (which can beretrieved withval()) or it is empty (in which case,val()will returnnull).- example
// Assume we have the following data in the Database:{"name": {"first":"Ada","last":"Lovelace" }}var ref = firebase.database().ref("users/ada");ref.once("value") .then(function(snapshot){var a = snapshot.hasChildren();// truevar b = snapshot.child("name").hasChildren();// truevar c = snapshot.child("name/first").hasChildren();// false });
Returnsboolean
true if this snapshot has any children; else false.
numChildren
- num
Children():number Returns the number of child properties of this
DataSnapshot.- example
// Assume we have the following data in the Database:{"name": {"first":"Ada","last":"Lovelace" }}var ref = firebase.database().ref("users/ada");ref.once("value") .then(function(snapshot){var a = snapshot.numChildren();// 1 ("name")var b = snapshot.child("name").numChildren();// 2 ("first", "last")var c = snapshot.child("name/first").numChildren();// 0 });
Returnsnumber
toJSON
- toJSON():Object |null
Returns a JSON-serializable representation of this object.
ReturnsObject |null
val
- val():any
Extracts a JavaScript value from a
DataSnapshot.Depending on the data in a
DataSnapshot, theval()method may return ascalar type (string, number, or boolean), an array, or an object. It may alsoreturn null, indicating that theDataSnapshotis empty (contains no data).- example
// Write and then read back a string from the Database.ref.set("hello") .then(function(){return ref.once("value"); }) .then(function(snapshot){var data = snapshot.val();// data === "hello" });- example
// Write and then read back a JavaScript object from the Database.ref.set({name:"Ada",age:36 }) .then(function(){return ref.once("value"); }) .then(function(snapshot){var data = snapshot.val();// data is { "name": "Ada", "age": 36 }// data.name === "Ada"// data.age === 36 });
Returnsany
The DataSnapshot's contents as a JavaScript value (Object,Array, string, number, boolean, or
null).
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 2023-09-28 UTC.