我假设可以这样做:
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?
谢谢
如果要生成一个唯一的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, { ... });
经过一些挖掘后,我在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;
}
}
我解压缩了方法(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生成我感觉更好。
希望这有助于/指导某人。
干杯。