AReference represents a specific location in your Database and can be usedfor reading or writing data to that Database location.
You can reference the root or child location in your Database by callingfirebase.database().ref() orfirebase.database().ref("child/path").
Writing is done with theset() method and reading can be done with theon() method. See Read and Write Data on the Web
Index
Properties
key
The last part of theReference's path.
For example,"ada" is the key forhttps://<DATABASE_NAME>.firebaseio.com/users/ada.
The key of a rootReference isnull.
- example
// The key of a root reference is nullvar rootRef = firebase.database().ref();var key = rootRef.key;// key === null- example
// The key of any non-root reference is the last token in the pathvar adaRef = firebase.database().ref("users/ada");var key = adaRef.key;// key === "ada"key = adaRef.child("name/last").key;// key === "last"
parent
The parent location of aReference.
The parent of a rootReference isnull.
- example
// The parent of a root reference is nullvar rootRef = firebase.database().ref();parent = rootRef.parent;// parent === null- example
// The parent of any non-root reference is the parent locationvar usersRef = firebase.database().ref("users");var adaRef = firebase.database().ref("users/ada");// usersRef and adaRef.parent represent the same location
ref
Returns aReference to theQuery's location.
root
The rootReference of the Database.
- example
// The root of a root reference is itselfvar rootRef = firebase.database().ref();// rootRef and rootRef.root represent the same location- example
// The root of any non-root reference is the root locationvar adaRef = firebase.database().ref("users/ada");// rootRef and adaRef.root represent the same location
Methods
child
- child(path: string):Reference
Gets a
Referencefor the location at the specified relative path.The relative path can either be a simple child name (for example, "ada") ora deeper slash-separated path (for example, "ada/name/first").
- 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'
Parameters
path:string
A relative path from this location to the desired childlocation.
ReturnsReference
The specified child location.
endAt
- end
At(value: number |string |boolean |null, key?: string):Query Creates a
Querywith the specified ending point.Using
startAt(),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 valuewill be included in the query. The optional key argument can be used tofurther limit the range of the query. If it is specified, then children thathave exactly the specified value must also have a key name less than or equalto the specified key.
You can read more about
endAt()in Filtering data.- example
// Find all dinosaurs whose names come before Pterodactyl lexicographically.// Include Pterodactyl in the result.var ref = firebase.database().ref("dinosaurs");ref.orderByKey().endAt("pterodactyl").on("child_added",function(snapshot){console.log(snapshot.key);});
Parameters
value:number |string |boolean |null
The value to end at. The argumenttype depends on which
orderBy*()function was used in this query.Specify a value that matches theorderBy*()type. When used incombination withorderByKey(), the value must be a string.Optional key:string
The child key to end at, among the children with thepreviously specified priority. This argument is only allowed if ordering bychild, value, or priority.
ReturnsQuery
endBefore
- end
Before(value: number |string |boolean |null, key?: string):Query Creates a
Querywith the specified ending point (exclusive).Using
startAt(),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, childrenwith a value less than the specified value will be included in the query.If a key is specified, then children must have a value lesss than or equalto the specified value and a a key name less than the specified key.
- example
// Find all dinosaurs whose names come before Pterodactyl lexicographically.// Do not include Pterodactyl in the result.var ref = firebase.database().ref("dinosaurs");ref.orderByKey().endBefore("pterodactyl").on("child_added",function(snapshot){console.log(snapshot.key);});@param value The value to end before. The argument type depends on which`orderBy*()`functionwasusedinthisquery.Specifyavaluethatmatchesthe `orderBy*()`type.Whenusedincombinationwith `orderByKey()`,thevaluemustbeastring.@paramkeyThechildkeytoendbefore,amongthechildrenwiththepreviouslyspecifiedpriority.Thisargumentisonlyallowediforderingbychild,value,orpriority.
Parameters
value:number |string |boolean |null
Optional key:string
ReturnsQuery
equalTo
- equal
To(value: number |string |boolean |null, key?: string):Query Creates a
Querythat includes children that match the specified value.Using
startAt(),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 thequery. If it is specified, then children that have exactly the specifiedvalue must also have exactly the specified key as their key name. This can beused to filter result sets with many matches for the same value.
You can read more about
equalTo()in Filtering data.- 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);});
Parameters
value:number |string |boolean |null
The value to match for. Theargument type depends on which
orderBy*()function was used in thisquery. Specify a value that matches theorderBy*()type. When used incombination withorderByKey(), the value must be a string.Optional key:string
The child key to start at, among the children with thepreviously specified priority. This argument is only allowed if ordering bychild, value, or priority.
ReturnsQuery
get
isEqual
- is
Equal(other: Query |null):boolean Returns whether or not the current and provided queries represent the samelocation, have the same query parameters, and are from the same instance of
firebase.app.App.Two
Referenceobjects are equivalent if they represent the same locationand are from the same instance offirebase.app.App.Two
Queryobjects are equivalent if they represent the same location, havethe same query parameters, and are from the same instance offirebase.app.App. Equivalent queries share the same sort order, limits, andstarting and ending points.- example
var rootRef = firebase.database.ref();var usersRef = rootRef.child("users");usersRef.isEqual(rootRef);// falseusersRef.isEqual(rootRef.child("users"));// trueusersRef.parent.isEqual(rootRef);// true- example
var rootRef = firebase.database.ref();var usersRef = rootRef.child("users");var usersQuery = usersRef.limitToLast(10);usersQuery.isEqual(usersRef);// falseusersQuery.isEqual(usersRef.limitToLast(10));// trueusersQuery.isEqual(rootRef.limitToLast(10));// falseusersQuery.isEqual(usersRef.orderByKey().limitToLast(10));// false
Parameters
other:Query |null
The query to compare against.
Returnsboolean
Whether or not the current and provided queries areequivalent.
limitToFirst
- limit
ToFirst(limit: number):Query Inherited fromQuery.limitToFirst
Generates a new
Querylimited to the first specific number of children.The
limitToFirst()method is used to set a maximum number of children to besynced for a given callback. If we set a limit of 100, we will initially onlyreceive up to 100child_addedevents. If we have fewer than 100 messagesstored in our Database, achild_addedevent will fire for each message.However, if we have over 100 messages, we will only receive achild_addedevent for the first 100 ordered messages. As items change, we will receivechild_removedevents for each item that drops out of the active list sothat the total number stays at 100.You can read more about
limitToFirst()in Filtering data.- 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);});
Parameters
limit:number
The maximum number of nodes to include in this query.
ReturnsQuery
limitToLast
- limit
ToLast(limit: number):Query Inherited fromQuery.limitToLast
Generates a new
Queryobject limited to the last specific number ofchildren.The
limitToLast()method is used to set a maximum number of children to besynced for a given callback. If we set a limit of 100, we will initially onlyreceive up to 100child_addedevents. If we have fewer than 100 messagesstored in our Database, achild_addedevent will fire for each message.However, if we have over 100 messages, we will only receive achild_addedevent for the last 100 ordered messages. As items change, we will receivechild_removedevents for each item that drops out of the active list sothat the total number stays at 100.You can read more about
limitToLast()in Filtering data.- 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);});
Parameters
limit:number
The maximum number of nodes to include in this query.
ReturnsQuery
off
- off(eventType?: EventType, callback?: (a: DataSnapshot, b?: string |null) =>any, context?: Object |null):void
Detaches a callback previously attached with
on().Detach a callback previously attached with
on(). Note that ifon()wascalled multiple times with the same eventType and callback, the callbackwill be called multiple times for each event, andoff()must be calledmultiple times to remove the callback. Callingoff()on a parent listenerwill 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 eventTypewill be removed. Similarly, if no eventType is specified, all callbacksfor the
Referencewill be removed.- example
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 callbacksref.child('meta-data').off('child_added', onValueAdded);- example
// 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);
Parameters
Optional eventType:EventType
One of the following strings: "value","child_added", "child_changed", "child_removed", or "child_moved." Ifomitted, all callbacks for the
Referencewill be removed.Optional callback:(a:DataSnapshot, b?:string |null) =>any
The callback function that was passed to
on()orundefinedto remove all callbacks.- (a:DataSnapshot, b?:string |null):any
Parameters
a:DataSnapshot
Optional b:string |null
Returnsany
Optional context:Object |null
The context that was passed to
on().
Returnsvoid
on
- on(eventType: EventType, callback: (a: DataSnapshot, b?: string |null) =>any, cancelCallbackOrContext?: ((a: Error) =>any) |Object |null, context?: Object |null):(a: DataSnapshot |null, b?: string |null) =>any
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callbackwill be triggered for the initial data and again whenever the data changes.Use
off( )to stop receiving updates. See Retrieve Data on the Webfor 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
DataSnapshotpassedto the callback will be for the location at whichon()was called. Itwon't trigger until the entire contents has been synchronized. If thelocation has no data, it will be triggered with an emptyDataSnapshot(val()will returnnull).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
DataSnapshotpassed into the callback will reflect the data for therelevant child. For ordering purposes, it is passed a second argument whichis a string containing the key of the previous sibling child by sort order,ornullif it is the first child.child_removed event
This event will be triggered once every time a child is removed. The
DataSnapshotpassed into the callback will be the old data for the childthat 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'ssort 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 itsdescendants) changes. Note that a single
child_changedevent may representmultiple changes to the child. TheDataSnapshotpassed to the callback willcontain the new child contents. For ordering purposes, the callback is alsopassed a second argument which is a string containing the key of the previoussibling child by sort order, ornullif it is the first child.child_moved event
This event will be triggered when a child's sort order changes such that itsposition relative to its siblings changes. The
DataSnapshotpassed to thecallback will be for the data of the child that has moved. It is also passeda second argument which is a string containing the key of the previoussibling child by sort order, ornullif it is the first child.- example
Handle a new value:
ref.on('value',function(dataSnapshot){ ...});- example
Handle a new child:
ref.on('child_added',function(childSnapshot, prevChildKey){ ...});- example
Handle child removal:
ref.on('child_removed',function(oldChildSnapshot){ ...});- example
Handle child data changes:
ref.on('child_changed',function(childSnapshot, prevChildKey){ ...});- example
Handle child ordering changes:
ref.on('child_moved',function(childSnapshot, prevChildKey){ ...});
Parameters
eventType:EventType
One of the following strings: "value","child_added", "child_changed", "child_removed", or "child_moved."
callback:(a:DataSnapshot, b?:string |null) =>any
Acallback that fires when the specified event occurs. The callback will bepassed a DataSnapshot. For ordering purposes, "child_added","child_changed", and "child_moved" will also be passed a string containingthe key of the previous child, by sort order, or
nullif it is thefirst child.- (a:DataSnapshot, b?:string |null):any
Parameters
a:DataSnapshot
Optional b:string |null
Returnsany
Optional cancelCallbackOrContext:((a:Error) =>any) |Object |null
An optionalcallback that will be notified if your event subscription is ever canceledbecause your client does not have permission to read this data (or it hadpermission but has now lost it). This callback will be passed an
Errorobject indicating why the failure occurred.Optional context:Object |null
If provided, this object will be used as
thiswhen calling your callback(s).
Returns(a:DataSnapshot |null, b?:string |null) =>any
The providedcallback function is returned unmodified. This is just for convenience ifyou want to pass an inline function to
on()but store the callbackfunction for later passing tooff().- (a:DataSnapshot |null, b?:string |null):any
Parameters
a:DataSnapshot |null
Optional b:string |null
Returnsany
- a client explicitly calls
onDisconnect
- on
Disconnect():OnDisconnect Returns an
OnDisconnectobject - see Enabling Offline Capabilities in JavaScript for more information on howto use it.ReturnsOnDisconnect
once
- once(eventType: EventType, successCallback?: (a: DataSnapshot, b?: string |null) =>any, failureCallbackOrContext?: ((a: Error) =>void) |Object |null, context?: Object |null):Promise<DataSnapshot>
Listens for exactly one event of the specified event type, and then stopslistening.
This is equivalent to calling
on(), andthen callingoff()inside the callbackfunction. Seeon()for details on theevent types.- example
// Basic usage of .once() to read the data located at ref.ref.once('value') .then(function(dataSnapshot){// handle read data. });
Parameters
eventType:EventType
One of the following strings: "value","child_added", "child_changed", "child_removed", or "child_moved."
Optional successCallback:(a:DataSnapshot, b?:string |null) =>any
Acallback that fires when the specified event occurs. The callback will bepassed a DataSnapshot. For ordering purposes, "child_added","child_changed", and "child_moved" will also be passed a string containingthe key of the previous child by sort order, or
nullif it is thefirst child.- (a:DataSnapshot, b?:string |null):any
Parameters
a:DataSnapshot
Optional b:string |null
Returnsany
Optional failureCallbackOrContext:((a:Error) =>void) |Object |null
An optionalcallback that will be notified if your client does not have permission toread the data. This callback will be passed an
Errorobject indicatingwhy the failure occurred.Optional context:Object |null
If provided, this object will be used as
thiswhen calling your callback(s).
ReturnsPromise<DataSnapshot>
orderByChild
- order
ByChild(path: string):Query Inherited fromQuery.orderByChild
Generates a new
Queryobject 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 definethem via the .indexOn rule in your Security Rules for better performance. Seethe.indexOn rule for more information.
You can read more about
orderByChild()in Sort data.- 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");});
Parameters
path:string
ReturnsQuery
orderByKey
- order
ByKey():Query Inherited fromQuery.orderByKey
Generates a new
Queryobject ordered by key.Sorts the results of a query by their (ascending) key values.
You can read more about
orderByKey()in Sort data.- example
var ref = firebase.database().ref("dinosaurs");ref.orderByKey().on("child_added",function(snapshot){console.log(snapshot.key);});
ReturnsQuery
orderByPriority
orderByValue
- order
ByValue():Query Inherited fromQuery.orderByValue
Generates a new
Queryobject ordered by value.If the children of a query are all scalar values (string, number, orboolean), you can order the results by their (ascending) values.
You can read more about
orderByValue()in Sort data.- 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()); });});
ReturnsQuery
push
- push(value?: any, onComplete?: (a: Error |null) =>any):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 is written to thegenerated location. If you don't pass a value, nothing is written to thedatabase and the child remains empty (but you can use theReferenceelsewhere).The unique keys generated by
push()are ordered by the current time, so theresulting list of items is chronologically sorted. The keys are alsodesigned to be unguessable (they contain 72 random bits of entropy).See Append to a list of dataSee The 2^120 Ways to Ensure Unique Identifiers
- example
var messageListRef = firebase.database().ref('message_list');var newMessageRef = messageListRef.push();newMessageRef.set({'user_id':'ada','text':'The Analytical Engine weaves algebraical patterns just as the Jacquard loom weaves flowers and leaves.'});// We've appended a new message to the message_list location.var path = newMessageRef.toString();// path will be something like// 'https://sample-app.firebaseio.com/message_list/-IKo28nwJLH0Nc5XeFmj'
Parameters
Optional value:any
Optional value to be written at the generated location.
Optional onComplete:(a:Error |null) =>any
Callback called when write to server iscomplete.
ReturnsThenableReference
Combined
PromiseandReference; resolves when write is complete, but can beused immediately as theReferenceto the child location.
remove
- remove(onComplete?: (a: Error |null) =>void):Promise<void>
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 correspondingevent 'value' will be triggered. Synchronization of the remove to theFirebase servers will also be started, and the returned Promise will resolvewhen complete. If provided, the onComplete callback will be calledasynchronously after synchronization has finished.
- example
var adaRef = firebase.database().ref('users/ada');adaRef.remove() .then(function(){console.log("Remove succeeded.") }) .catch(function(error){console.log("Remove failed: " + error.message) });
Parameters
Optional onComplete:(a:Error |null) =>void
Callback called when write to server iscomplete.
ReturnsPromise<void>
Resolves when remove on server is complete.
set
- set(value: any, onComplete?: (a: Error |null) =>void):Promise<void>
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 correspondingevents ("value", "child_added", etc.) will be triggered. Synchronization ofthe data to the Firebase servers will also be started, and the returnedPromise will resolve when complete. If provided, the
onCompletecallbackwill be called asynchronously after synchronization has finished.Passing
nullfor 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 ismeant to be preserved, you need to usesetWithPriority()instead.Note that modifying data with
set()will cancel any pending transactionsat that location, so extreme care should be taken if mixingset()andtransaction()to modify the same data.A single
set()will generate a single "value" event at the location wheretheset()was performed.- example
var adaNameRef = firebase.database().ref('users/ada/name');adaNameRef.child('first').set('Ada');adaNameRef.child('last').set('Lovelace');// We've written 'Ada' to the Database location storing Ada's first name,// and 'Lovelace' to the location storing her last name.- example
adaNameRef.set({first:'Ada',last:'Lovelace' });// Exact same effect as the previous example, except we've written// Ada's first and last name simultaneously.- example
adaNameRef.set({first:'Ada',last:'Lovelace' }) .then(function(){console.log('Synchronization succeeded'); }) .catch(function(error){console.log('Synchronization failed'); });// Same as the previous example, except we will also log a message// when the data has finished synchronizing.
Parameters
value:any
The value to be written (string, number, boolean, object,array, or null).
Optional onComplete:(a:Error |null) =>void
Callback called when write to server iscomplete.
ReturnsPromise<void>
Resolves when write to server is complete.
setPriority
- set
Priority(priority: string |number |null, onComplete: (a: Error |null) =>void):Promise<void> Sets a priority for the data at this Database location.
Applications need not use priority but can order collections byordinary properties (see Sorting and filtering data).
Parameters
priority:string |number |null
onComplete:(a:Error |null) =>void
ReturnsPromise<void>
setWithPriority
- set
With Priority(newVal: any, newPriority: string |number |null, onComplete?: (a: Error |null) =>void):Promise<void> Writes data the Database location. Like
set()but also specifies thepriority for that data.Applications need not use priority but can order collections byordinary properties (see Sorting and filtering data).
Parameters
newVal:any
newPriority:string |number |null
Optional onComplete:(a:Error |null) =>void
ReturnsPromise<void>
startAfter
- start
After(value: number |string |boolean |null, key?: string):Query Inherited fromQuery.startAfter
Creates a
Querywith the specified starting point (exclusive).Using
startAt(),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, childrenwith 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 equalto the specified value and a a key name greater than the specified key.
- example
// Find all dinosaurs that are more than three meters tall.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").startAfter(3).on("child_added",function(snapshot){console.log(snapshot.key)});
Parameters
value:number |string |boolean |null
The value to start after. The argumenttype depends on which
orderBy*()function was used in this query.Specify a value that matches theorderBy*()type. When used incombination withorderByKey(), the value must be a string.Optional key:string
The child key to start after. This argument is only allowedif ordering by child, value, or priority.
ReturnsQuery
startAt
- start
At(value: number |string |boolean |null, key?: string):Query Creates a
Querywith the specified starting point.Using
startAt(),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 valuewill be included in the query. The optional key argument can be used tofurther limit the range of the query. If it is specified, then children thathave exactly the specified value must also have a key name greater than orequal to the specified key.
You can read more about
startAt()in Filtering data.- example
// Find all dinosaurs that are at least three meters tall.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").startAt(3).on("child_added",function(snapshot){console.log(snapshot.key)});
Parameters
value:number |string |boolean |null
The value to start at. The argumenttype depends on which
orderBy*()function was used in this query.Specify a value that matches theorderBy*()type. When used incombination withorderByKey(), the value must be a string.Optional key:string
The child key to start at. This argument is only allowedif ordering by child, value, or priority.
ReturnsQuery
toJSON
toString
transaction
- transaction(transactionUpdate: (a: any) =>any, onComplete?: (a: Error |null, b: boolean, c: DataSnapshot |null) =>void, applyLocally?: boolean):Promise<TransactionResult>
Atomically modifies the data at this location.
Atomically modify the data at this location. Unlike a normal
set(), whichjust overwrites the data regardless of its previous value,transaction()isused to modify the existing value to a new value, ensuring there are noconflicts with other clients writing to the same location at the same time.To accomplish this, you pass
transaction()an update function which is usedto transform the current value into a new value. If another client writes tothe location before your new value is successfully written, your updatefunction will be called again with the new current value, and the write willbe retried. This will happen repeatedly until your write succeeds withoutconflict or you abort the transaction by not returning a value from yourupdate function.Note: Modifying data with
set()will cancel any pending transactions atthat location, so extreme care should be taken if mixingset()andtransaction()to update the same data.Note: When using transactions with Security and Firebase Rules in place, beaware that a client needs
.readaccess in addition to.writeaccess inorder to perform a transaction. This is because the client-side nature oftransactions requires the client to read the data in order to transactionallyupdate it.- example
// Increment Ada's rank by 1.var adaRankRef = firebase.database().ref('users/ada/rank');adaRankRef.transaction(function(currentRank){// If users/ada/rank has never been set, currentRank will be `null`.return currentRank +1;});- example
// Try to create a user for ada, but only if the user id 'ada' isn't// already takenvar adaRef = firebase.database().ref('users/ada');adaRef.transaction(function(currentData){if (currentData ===null) {return {name: {first:'Ada',last:'Lovelace' } }; }else {console.log('User ada already exists.');return;// Abort the transaction. }},function(error, committed, snapshot){if (error) {console.log('Transaction failed abnormally!', error); }elseif (!committed) {console.log('We aborted the transaction (because ada already exists).'); }else {console.log('User ada added!'); }console.log("Ada's data: ", snapshot.val());});
Parameters
transactionUpdate:(a:any) =>any
A developer-supplied function whichwill be passed the current data stored at this location (as a JavaScriptobject). The function should return the new value it would like written (asa JavaScript object). If
undefinedis returned (i.e. you return with noarguments) the transaction will be aborted and the data at this locationwill not be modified.- (a:any):any
Parameters
a:any
Returnsany
Optional onComplete:(a:Error |null, b:boolean, c:DataSnapshot |null) =>void
A callbackfunction that will be called when the transaction completes. The callbackis passed three arguments: a possibly-null
Error, abooleanindicatingwhether the transaction was committed, and aDataSnapshotindicating thefinal result. If the transaction failed abnormally, the first argument willbe anErrorobject indicating the failure cause. If the transactionfinished normally, but no data was committed because no data was returnedfromtransactionUpdate, then second argument will be false. If thetransaction completed and committed data to Firebase, the second argumentwill be true. Regardless, the third argument will be aDataSnapshotcontaining the resulting data in this location.- (a:Error |null, b:boolean, c:DataSnapshot |null):void
Parameters
a:Error |null
b:boolean
c:DataSnapshot |null
Returnsvoid
Optional applyLocally:boolean
By default, events are raised each time thetransaction update function runs. So if it is run multiple times, you maysee intermediate states. You can set this to false to suppress theseintermediate states and instead wait until the transaction has completedbefore events are raised.
ReturnsPromise<TransactionResult>
Returns a Promise that can optionally be used instead of the onCompletecallback to handle success and failure.
update
- update(values: Object, onComplete?: (a: Error |null) =>void):Promise<void>
Writes multiple values to the Database at once.
The
valuesargument contains multiple property-value pairs that will bewritten to the Database together. Each child property can either be a simpleproperty (for example, "name") or a relative path (for example,"name/first") from the current location to the data to update.As opposed to the
set()method,update()can be use to selectively updateonly the referenced properties at the current location (instead of replacingall the child properties at the current location).The effect of the write will be visible immediately, and the correspondingevents ('value', 'child_added', etc.) will be triggered. Synchronization ofthe data to the Firebase servers will also be started, and the returnedPromise will resolve when complete. If provided, the
onCompletecallbackwill be called asynchronously after synchronization has finished.A single
update()will generate a single "value" event at the locationwhere theupdate()was performed, regardless of how many children weremodified.Note that modifying data with
update()will cancel any pendingtransactions at that location, so extreme care should be taken if mixingupdate()andtransaction()to modify the same data.Passing
nulltoupdate()will remove the data at this location.See Introducing multi-location updates and more.
- example
var adaNameRef = firebase.database().ref('users/ada/name');// Modify the 'first' and 'last' properties, but leave other data at// adaNameRef unchanged.adaNameRef.update({first:'Ada',last:'Lovelace' });
Parameters
values:Object
Object containing multiple values.
Optional onComplete:(a:Error |null) =>void
Callback called when write to server iscomplete.
ReturnsPromise<void>
Resolves when update on server is complete.
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 2022-07-27 UTC.