Auto increment data on firebase

Deadly 提交于 2019-12-25 16:42:16

问题


I am currently trying to create something like this on Firebase:

"Assets": {
    "asset001" : {
        "name": "DESK001",
        "owner: "owner's name",
        "brand: "HP",
    },
   "asset002" : {
        "name": "NOTE001",
        "owner: "owner's name",
        "brand: "Dell",
    },

   ...
}

But, i dont know how to automatically increment the value on "asset001"... i have seen the push() method, but then i wouldn't know how to retrieve the data. Here's what i have so far:

JavaScript

//Get the inputs ID from HTML
var inputName = document.getElementById("inputName");
var inputOwner = document.getElementById("inputOwner");
var inputBrand = document.getElementById("inputBrand");
var inputAsset = document.getElementById("inputAsset");

//Set values on FireBase    
btnAsset.addEventListener('click', e => {
//Get inputs data
const asset = inputAsset.value;
const owner = inputOwner.value;
const brand = inputBrand.value;
const name = inputName.value;

//database reference
var rootRef = firebase.database().ref().child("Assets");

//setar os valores
rootRef.child(asset).child("owner").set(owner);
rootRef.child(asset).child("brand").set(brand);
rootRef.child(asset).child("name").set(name);

回答1:


You seem to be going through a lot of trouble trying to make names for your assets. The way you are creating your keys you will run into trouble once you reach Asset999.

The best way to ensure that you do not have to bother with creating a unique key is letting firebase do it for you. Then upload all the info in one go.

var newKey = rootRef.push().key;

var objectToUpload = {
"owner": owner,
"brand": brand,
"name": name
};

rootRef.child(newKey).set(objectToUpload);


来源:https://stackoverflow.com/questions/43969427/auto-increment-data-on-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!