📜  firebase.database.ServerValue.increment - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:12.667000             🧑  作者: Mango

Firebase.database.ServerValue.increment - Javascript

Firebase.database.ServerValue.increment is a special value provided by the Firebase Realtime Database SDK for Javascript that allows you to atomically increment a value in your database.

Syntax

To increment a value:

firebase.database().ref('path/to/count').update({
  count: firebase.database.ServerValue.increment(1)
});

Parameters

  • amount (number): The amount to increment the value by. This can be positive or negative.

Return Value

Firebase.database.ServerValue.increment returns an object containing a special sentinel value. When you write this object to the database, the server increments the current value at the specified location by the amount provided.

Example

// Assume that 'path/to/count' has a value of 5 in the database
firebase.database().ref('path/to/count').update({
  count: firebase.database.ServerValue.increment(2)
});
// The value at 'path/to/count' is now 7

Notes

  • The increment operation is atomic and cannot be interleaved with other writes to the same location.
  • Incrementing an non-existing node will create the node and set its value to the specified amount.
  • The increment amount can be negative, which effectively decrements the value.
  • Server timestamps can be combined with increment values in a single update().
  • Firebase.database.ServerValue.increment can only be used with the update() method or as a value in a transaction, not with set().

Conclusion

Firebase.database.ServerValue.increment is a useful tool for incrementing values in your Firebase Realtime Database using an atomic operation. It works by returning a special object that tells the Firebase server to increment the value at a given location by a specified amount. Just be sure to use it with update() or in a transaction to ensure atomicity.