Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase - Firestore - get key with collection.add()

Tags:

I am facing a problem with the new Firestore from Firebase.

Situation: I have a collection('room')

I create room with collection('room').add(room)


What I'm trying to do: I need to update a room.

For this, I use: collection('room').doc(ROOM_ID).update(update)

So I need to add ROOM_ID in the document in my collection:

|room     ROOM_ID         id:ROOM_ID,         someContent: ForTheQuery 

Is there a possible way to achieve that?

An alternative is to create myself a generated ID with:

collection('room') .doc(someId) .set({     id: someId,     someContent: ForTheQuery }); 

but i want to avoid it.

like image 571
Wandrille Avatar asked Oct 14 '17 18:10

Wandrille


People also ask

How do I find my firestore key?

All the custom Objects that you store in the Firestore behave just like the native Javascript objects. To get all keys of an object, you can simply use the Object. keys() method that is available for all the Objects in Javascript.

How do I get my ID after adding firestore?

When you call the . add method on a collection, a DocumentReference object is returned. DocumentReference has the id field, so you can get the id after the document was created. // Add a new document with a generated id.


1 Answers

You can use doc() to create a reference to a document with a unique id, but the document will not be created yet. You can then set the contents of that doc by using the unique id that was provided in the document reference:

const ref = store.collection('users').doc() console.log(ref.id)  // prints the unique id ref.set({id: ref.id})  // sets the contents of the doc using the id .then(() => {  // fetch the doc again and show its data     ref.get().then(doc => {         console.log(doc.data())  // prints {id: "the unique id"}     }) }) 
like image 115
Doug Stevenson Avatar answered Oct 29 '22 15:10

Doug Stevenson