简体   繁体   English

如何增加 Firebase 实时数据库 (v9) 中的值

[英]How to increment values in Firebase Realtime Database (v9)

I note that there's instructions on how to increment values for realtime database in Javascript v8:我注意到在 Javascript v8 中有关于如何增加实时数据库值的说明:

=== ===

Added ServerValue.increment() to support atomic field value increments without transactions.添加了 ServerValue.increment() 以支持无事务的原子字段值增量。

API Docs here API 文档在这里

Usage example:使用示例:

firebase.database()
    .ref('node')
    .child('clicks')
    .set(firebase.database.ServerValue.increment(1))

Or you can decrement, just put -1 as function arg like so:或者您可以递减,只需将 -1 设为 function arg,如下所示:

firebase.database()
    .ref('node')
    .child('clicks')
    .set(firebase.database.ServerValue.increment(-1))

However, I notice that there isn't any reference to ServerValue in the v9 documentation.但是,我注意到 v9 文档中没有对 ServerValue 的任何引用。

Does this mean that this functionality is not available?这是否意味着此功能不可用?

I've tried converting it to v9 on my own but I've been unsuccessful so far:我已经尝试自己将其转换为 v9,但到目前为止我还没有成功:

const setWeekComplete = () => {
    set(ref(database, `users/${user}/streakCounter`), {
        weeks: database.ServerValue.increment(1)
    });
  }    

It is still available in V9 and you'll find it here in the doc .它在 V9 中仍然可用,您可以在 doc 中找到它。 So the following should do the trick.因此,以下应该可以解决问题。

import { ... , increment } from 'firebase/database';

// ...

const setWeekComplete = async () => {
    await set(ref(database, `users/${user}/streakCounter`), {
        weeks: increment(1)
    });
  } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM