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

后端 未结 4 749
渐次进展
渐次进展 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 }) {
        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;
      }
    

提交回复
热议问题