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

firebase firestore在事务中添加新文档-transaction.add不是一个函数,firebase,react-native,transactions,google-cloud-firestore,Firebase,React Native,Transactions,Google Cloud Firestore,我假设可以这样做: transaction.add(collectionRef,{ uid: userId, name: name, fsTimestamp: firebase.firestore.Timestamp.now(), }); 但显然不是: transaction.add不是一个函数 上述信息显示在chrome控制台内 我发现我们可以使用事务的set方法以事务方式添加新文档。见: 问题是,如果我使用set而不是add(无论如何都不支持),那么文档的id应该由我手动创建,

我假设可以这样做:

transaction.add(collectionRef,{
  uid: userId,
  name: name,
  fsTimestamp: firebase.firestore.Timestamp.now(),
});
但显然不是:

transaction.add不是一个函数

上述信息显示在chrome控制台内

我发现我们可以使用事务的set方法以事务方式添加新文档。见:

问题是,如果我使用set而不是add(无论如何都不支持),那么文档的id应该由我手动创建,firestore不会创建它。 见:

如果没有自动为您生成id的add方法,您认为这有什么坏处吗

例如,firestore本身生成的id是否可能在考虑性能等各种问题的情况下进行了优化

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


谢谢

经过进一步挖掘,我在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;
  }
}
由于我使用与firestore本身相同的id生成算法,我感觉好多了

希望这能帮助/指导某人


干杯。

如果您想生成一个唯一的ID供以后在事务中创建文档时使用,您所要做的就是不带参数地生成DocumentReference,您可以在事务中稍后设置它()

(你在回答中提出的建议是,为了达到同样的效果,需要做更多的工作。)


根据Doug Stevenson的回答,这就是我如何使用@angular/fire的方法:

// Create a reference to a document and provide it a random id, e.g. by using uuidv4
const newDocRef = this.db.collection('coll').doc(uuidv4()).ref;

// In the transaction:
transaction.set(newDocRef, { ... });

完成Stefan的回答。对于使用Angularfire的用户,5.2版之前使用CollectionReference.doc()会导致错误“CollectionReference.doc()要求其第一个参数的类型为非空字符串”

这个变通方法对我很有效:

const id = this.afs.createId();
const ref = this.afs.collection(this.collectionRef).doc(id);
transaction.set(ref, { ... });

信用证:

By
db.collectionRef
您的意思是
db.collection
,对吗?@DougStevenson-hmm,当我尝试此操作时,我有一个错误:FirebaseError:Function CollectionReference.doc()要求其第一个参数的类型为非空字符串,但它是:undefined。有任何更新吗?好的,我可以看到,angularfire不起作用:/@DougStevenson:这是否意味着文档id被保留了?如果是:是否需要在事务中调用doc()?或者我们是否依赖id生成器在另一个无关调用中不提供统计值?
// Create a reference to a document that doesn't exist yet, it has a random id
const newDocRef = db.collection('coll').doc();

// Then, later in a transaction:
transaction.set(newDocRef, { ... });
// Create a reference to a document and provide it a random id, e.g. by using uuidv4
const newDocRef = this.db.collection('coll').doc(uuidv4()).ref;

// In the transaction:
transaction.set(newDocRef, { ... });
const id = this.afs.createId();
const ref = this.afs.collection(this.collectionRef).doc(id);
transaction.set(ref, { ... });