Firebase - Firestore - 使用 collection.add() 获取密钥

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

我在使用 Firebase 的新 Firestore 时遇到问题。

情况:我有一个collection('room')

我用 collection('room').add(room)

创建房间

我想做什么:我需要更新房间。

为此,我使用:collection('room').doc(ROOM_ID).update(update)

所以我需要在我的collection的文档中添加ROOM_ID:

|room
    ROOM_ID
        id:ROOM_ID,
        someContent: ForTheQuery

有没有可能实现的方法?

另一种方法是为自己创建一个生成的 ID:

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

但我想避免它。

您可以使用 doc() 来创建对具有唯一 ID 的文档的引用,但该文档不会被创建。然后,您可以使用文档参考中提供的唯一 ID 来设置该文档的内容:

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

角火:

添加数据库前获取ID:

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

ANDROID FIRESTORE:

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

您可以使用 collection.ref.add(您没有 ID 的项目)从创建的文档中获取 ID,并且响应 (res) 将包含使用其中的 ID 创建的新文档引用。因此,只需执行 res.id.

即可获取 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 Javascript SDK:

只需使用 .id 即可获取密钥,这里是使用 async/ await 的示例:

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