firebase firestore在事务中添加新文档 - transaction.add不是函数

问题描述 投票:0回答:2

我假设可以这样做:

transaction.add(collectionRef,{
  uid: userId,
  name: name,
  fsTimestamp: firebase.firestore.Timestamp.now(),
});

但显然它不是:

transaction.add不是一个函数

以上消息显示在chrome控制台内。

我看到我们可以使用事务的set方法以事务方式添加新文档。见:https://firebase.google.com/docs/firestore/manage-data/transactions

问题是如果我使用set而不是add(反正不支持),文档的id应该由我手动创建,firestore不会创建它。见:https://firebase.google.com/docs/firestore/manage-data/add-data

你有没有看到没有自动为你生成id的add方法的缺点?

例如,考虑到包括性能在内的各种问题,是否可能以某种方式优化firestore本身生成的id?

在使用transaction.set时,您使用哪个库/方法在react-native中创建文档ID?

谢谢

firebase react-native transactions google-cloud-firestore
2个回答
2
投票

如果要生成一个唯一的ID以供稍后在事务中创建文档时使用,您所要做的就是使用没有参数的CollectionReference.doc()来生成DocumentReference,您可以在事务中稍后设置()。

(你在答案中提出的建议是为同样的效果做更多工作。)

// Create a reference to a document that doesn't exist yet, it has a random id
const newDocRef = db.collectionRef('coll').doc();

// Then, later in a transaction:
transaction.set(newDocRef, { ... });

0
投票

经过一些挖掘后,我在firestore本身的源代码中找到了id生成的下面的类/方法:

export class AutoId {
  static newId(): string {
    // Alphanumeric characters
    const chars =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let autoId = '';
    for (let i = 0; i < 20; i++) {
      autoId += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);
    return autoId;
  }
}

见:https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36

我解压缩了方法(assert语句除外)并将其放在我的代码中的方法中。然后我使用事务的set方法如下:

generateFirestoreId(){
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let autoId = '';
        for (let i = 0; i < 20; i++) {
            autoId += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        //assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);
        return autoId;
    }

然后,

newDocRef = db.collection("PARENTCOLL").doc(PARENTDOCID).collection('SUBCOLL').doc(this.generateFirestoreId());
                        transaction.set(newDocRef,{
                            uid: userId,
                            name: name,
                            fsTimestamp: firebase.firestore.Timestamp.now(),
                        });

因为我使用相同的算法作为火葬场本身的id生成我感觉更好。

希望这有助于/指导某人。

干杯。

© www.soinside.com 2019 - 2024. All rights reserved.