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

后端 未结 4 739
渐次进展
渐次进展 2020-12-01 16:31

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

Situation: I have a collection(\'room\')

I create room with c

相关标签:
4条回答
  • 2020-12-01 16:39

    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;
      }
    
    0 讨论(0)
  • 2020-12-01 16:42

    ANGULARFIRE:

    get ID before add database:

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

    ANDROID FIRESTORE:

    String idBefore = db.collection("YourCol").document().getId();
    
    0 讨论(0)
  • 2020-12-01 16:58

    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;
    
    0 讨论(0)
  • 2020-12-01 17:02

    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"}
        })
    })
    
    0 讨论(0)
提交回复
热议问题