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

firestore get document id
firestore add document with custom id
firestore add document with auto id
get all documents in collection firestore
firestore add multiple documents
firestore add collection
firestore getall
firestore create collection

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.

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"}
    })
})

Get data with Cloud Firestore, Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive� Cloud Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects. Cloud Firestore always stores numbers as doubles, regardless of what type of number you use in your code.

ANGULARFIRE:

get ID before add database:

var idBefore =  afs.createId();
    console.log(idBefore );

ANDROID FIRESTORE:

String idBefore = db.collection("YourCol").document().getId();

Add data to Cloud Firestore, Get started � Connect to the Realtime Database emulator � Connect to the Key concepts and strategies Set the data of a document within a collection, explicitly specifying a how to use the set, add, or update individual documents in Cloud Firestore. To create or overwrite a single document, use the set() method:. You can deploy rules in the Firebase console or using the Firebase CLI. Updates to Cloud Firestore Security Rules can take up to a minute to affect new queries and listeners. However, it can take up to 10 minutes to fully propagate the changes and affect any active listeners.

You can get the ID from the created document by using collection.ref.add(your item without id) and the response (res) will contain the new document reference created with the ID inside it. So get the ID by simply doing res.id.

  createOne(options: { item: any, ref: AngularFirestoreCollection<any> }) {
    const promise = new Promise((resolve, reject) => {

      if (options.item) {
        // Convert object to pure javascript
        const item = Object.assign({}, options.item);
        console.log('dataService: createOne: set item: ', item);

        options.ref.ref.add(item)
          .then((res) => {
            console.log('dataService: createOne success: res: ', res);
            resolve(res);
          }).catch(err => {
            console.error('dataService: createOne: error: ', err);
            reject(err);
          });
      } else {
        console.log('dataService: createOne: wrong options! options: ', options);
        reject();
      }
    })

    return promise;
  }

Firebase - Firestore - get key with collection.add() - firebase - html, Firebase Javascript SDK: Just use .id to get the key, here is an example using async/ await : const KEYID = async() => (await fs.collection("testing").add({ data:� Getting the unique key generated by push() Calling push() will return a reference to the new data path, which you can use to get the key or set data to it. The following code will result in the same data as the above example, but now we'll have access to the unique key that was generated:

Firebase Javascript SDK:

Just use .id to get the key, here is an example using async/ await :

  const KEYID = async() => (await fs.collection("testing").add({ data: 'test'})).id;

Firebase - Firestore - get key with collection.add(), Firebase - Firestore - get key with collection.add(). firebase google-cloud-firestore . I am facing a problem with the new Firestore from Firebase. Situation: I have a� Cloud Firestore supports atomic operations for reading and writing data. In a set of atomic operations, either all of the operations succeed, or none of them are applied.

Adding data | Firestore, Cloud Key Management Service Set the data of a document within a collection, explicitly specifying a To create or overwrite a single document, use the set() method: future.get() blocks on response System.out.println("Update time : " + Important: Unlike "push IDs" in the Firebase Realtime Database, Firestore� These queries can also be used with either get() or addSnapshotListener(), as described in Get Data and Get Realtime Updates. Note: While the code samples cover multiple languages, the text explaining the samples refers to the Web method names. Example data. To get started, write some data about cities so we can look at different ways to read

Querying and filtering data | Firestore, to retrieve from a collection or collection group. These queries can also be used with either get() or addSnapshotListener() , as described in Get Data and Get� For angular 8 and Firebase 6 you can use the option id field . getAllDocs() { const ref = this.db.collection('items'); return ref.valueChanges({idField: 'customIdName'}); } this adds the Id of the document on the object with a specified key (customIdName)

DocumentReference, let collectionRef = firestore.collection('col'); collectionRef.add({foo: let documentRef = firestore.doc('col/doc'); documentRef.get().then( documentSnapshot => { if The update() method accepts either an object with field paths encoded as keys post.title, author: post.author}; }, fromFirestore( snapshot: FirebaseFirestore. Browse other questions tagged javascript firebase google-cloud-firestore or ask your own question. The Overflow Blog Nobody has to lose in work/life balance

Comments
  • I don't see a problem with your proposed solution. Why don't you want to do it that way?
  • Because I'm not certain about the function of generation for ID. I see con and pro for each function so I wont to keep it clean with firebase generation iD.
  • So you're asking here how you can add a document with a generated I'd, and also add that id as a property of that document itself?
  • @Doug Stevenson Yes this is right. And I want to avoid duplicated keys. And I imagine (that can be completely false, correct me if it does not) that Firebase will never have duplicated keys with some checkings. Thanks for your concern.
  • I think it should be noted that setting the id as a field in the ref doc is redundent. I'm referring to the 'ref.set({id: ref.id})' statement.
  • @Tom this can come in handy when you need the unique ID of the document to participate in automatic deserialization. So, if you have a JavaBean object where the doucment ID should be one of the properties of the object, this will arrange for that property to be automatically set in that object. This avoids having to write extra code to do that for each deserialization.
  • Could this id be used by another request that is running in parallel, for example? How can we assure the integrity of this id and this request that is being executed? Is it thread-safe?
  • @LMGagne You can use this id any way you want. Threadsafety is never an issue, since there is only ever one connection and all operations are pipelined over it. Not sure what you mean by "integrity".
  • Could it be possible for two functions to pull the same id? In this case, the data integrity could also be compromised.
  • Thanks, this is right: they use it in the doc: github.com/angular/angularfire2/blob/master/docs/firestore/…