firebase firestore 在事务中添加新文档 - transaction.add 不是函数 [英] firebase firestore addding new document inside a transaction - transaction.add is not a function

查看:15
本文介绍了firebase firestore 在事务中添加新文档 - transaction.add 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我假设可以执行以下操作:

I was assuming that it was possible to do something like:

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

但显然不是:

transaction.add 不是函数

transaction.add is not a function

上述消息显示在 chrome 控制台内.

The above message is displayed inside the chrome console.

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

I see that we can use the set method of the transaction to add a new document transactionally. see: https://firebase.google.com/docs/firestore/manage-data/transactions

问题是,如果我使用 set 而不是 add(无论如何都不支持),文档的 id 应该由我手动创建,firestore 不会创建它.请参阅:https://firebase.google.com/docs/firestore/manage-数据/添加数据

The thing is if I use set instead of add(which is not supported anyways), the id of the document should be created by me manually, firestore won't create it. see: https://firebase.google.com/docs/firestore/manage-data/add-data

您是否看到没有自动为您生成 ID 的 add 方法的任何缺点?

Do you see any downside of this not having an add method that generates the id for you automatically?

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

For example, is it possible that the id generated by the firestore itself is somehow optimized considering various concerns including performance?

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

Which library/method do you use to create your document IDs in react-native while using transaction.set?

谢谢

推荐答案

如果您想生成一个唯一的 ID 以供以后在事务中创建文档时使用,您只需使用 CollectionReference.doc() 没有参数来生成您可以设置的 DocumentReference()稍后在交易中.

If you want to generate a unique ID for later use in creating a document in a transaction, all you have to do is use CollectionReference.doc() with no parameters to generate a DocumentReference which you can set() later in a transaction.

(你在答案中提出的是为了同样的效果,需要更多的工作.)

(What you're proposing in your answer is way more work for the same effect.)

// 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, { ... });

这篇关于firebase firestore 在事务中添加新文档 - transaction.add 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆