本文介绍了添加具有自动递增的自定义ID的子项-Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自动增量ID向Firebase数据库添加一个新用户,如以下屏幕截图所示:

I want to add a new user to firebase database with auto increment id as shown below screenshots:

我尝试过:

    var rootRef = firebase.database().ref();
    var storesRef = rootRef.child("/users");
    storesRef.set({
      "name": "user1",
      "pageId": "user1"
    });

推荐答案

我不推荐这样做,但您可以尝试以下操作:

I do not recommend this, but you can try the following:

storesRef.limitToLast(1).once('value', (snapshot) => {
    const nextID = parseInt(snapshot.key) + 1;
    let updates = {};
    updates['/users/' + nextID] = // your user;
    rootRef.update(updates);
});

但是,我强烈建议您改用Firebases自动生成的ID,因为这种方法很容易出错.

However, I would strongly suggest you use Firebases automatically generated IDs instead, since this approach is very error prone.

您还应该查看此答案.

这篇关于添加具有自动递增的自定义ID的子项-Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:12