Jaffer Abyan Syed
Jaffer Abyan Syed

Reputation: 129

how to make an id in a realtime database

I am trying to add a unique ID to certain objects to item information that I am inputting in the real-time database.

here is my code that I am trying to implement.

        database.ref('item/' + /*Here is where I would add the uniqueUD*/ ).set({
          ItemName: ItemName,
          Address: ItemAddress,
          Industry: ItemIndustry,
          Speciality: ItemSpeciality,
          Description: ItemDescription
        })

I am trying to have the database look like.

(ItemIndex) - (Item ID) - ItemName, ItemAddress, ItemIndustry, ItemSpeciality, ItemDescription

Upvotes: 1

Views: 4951

Answers (3)

dashb
dashb

Reputation: 157

2023 v9 modules syntax example of how to get the ID first:

const itemRef = ref(database, `users/${userId}/items`)
const addedItem = await push(itemRef)
console.log(addedItem.key, "This is the ID you're looking for")

await set(addedItem, {
    ...{ exampleData: 'example' },
    id: addedItem.key, // You could insert the same ID into the item if you wanted to.
})

Upvotes: 1

Arnelle Balane
Arnelle Balane

Reputation: 5487

A reference's .push() method creates a new reference even if you don't pass any value to it. From the docs:

If you don't pass a value, nothing will be written to the Database and the child will remain empty (but you can use the Reference elsewhere).

This means you can create a new reference using this method without having to write anything to the db:

const ref = database.ref('item').push();

You can then use Firebase's generated unique ID from ref.key. You can include this value in your data if you want. When you are ready to write data to the same ref, you can call its .set() method.

ref.set({
    ItemName: ItemName,
    Address: ItemAddress,
    Industry: ItemIndustry,
    Speciality: ItemSpeciality,
    Description: ItemDescription
});

Upvotes: 3

Ben Lorantfy
Ben Lorantfy

Reputation: 963

Firebase will create an ID for you if you use push instead of set:

    database.ref('item').push({
      ItemName: ItemName,
      Address: ItemAddress,
      Industry: ItemIndustry,
      Speciality: ItemSpeciality,
      Description: ItemDescription
    })

See docs: https://firebase.google.com/docs/database/admin/save-data#section-push

Upvotes: 5

Related Questions