是否可以在添加之前获得 ID?

我知道在 Realtime Database中我可以得到 push ID,在它像这样被添加之前:

 DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
String challengeId=databaseReference.push().getKey();

然后我可以用这个 ID 把它加进去。

Can I get it also in the Cloud Firestore?

88436 次浏览

这在 文件中已经介绍过了。请参阅添加文档部分的最后一段。

DocumentReference ref = db.collection("my_collection").doc();
String myId = ref.id;

您可以按照以下方式进行此操作(代码是 AngularFire2 v5,类似于任何其他版本的 firebase SDK,比如 web、 node 等)

const pushkey = this.afs.createId();
const project = {' pushKey': pushkey, ...data };
this.projectsRef.doc(pushkey).set(project);

projectsRef is firestore collection reference.

Data 是一个带有键值的对象,您希望将该值上载到 firestore。

Afs 是构造函数中注入的角度恢复模块。

This will generate a new document at Collection called projectsRef, with its id as pushKey and that document will have pushKey property same as id of document.

记住,set 还会删除任何现有数据

事实上。Add ()和。Doc ().Set ()是相同的操作。但是。Add () id 是自动生成的,并且具有。Doc ().Set ()可以提供自定义 ID。

const db = firebase.firestore();
const ref = db.collection('your_collection_name').doc();
const id = ref.id;

IDK,如果这有帮助的话,但是我想要得到文档的 id,从火灾恢复数据库-也就是说,数据已经输入到控制台。

我想要一个简单的方法来动态访问这个 ID,所以我简单地将它添加到文档对象,如下所示:

const querySnapshot = await db.collection("catalog").get();
querySnapshot.forEach(category => {
const categoryData = category.data();
categoryData.id = category.id;

现在,我可以访问 id就像访问其他属性一样。

IDK 为什么 id不仅仅是 .data()的一部分摆在首位!

This works for me. I update the document while in the same transaction. I create the document and immediately update the document with the document Id.

        let db = Firestore.firestore().collection(“cities”)


var ref: DocumentReference? = nil
ref = db.addDocument(data: [
“Name” : “Los Angeles”,
“State: : “CA”
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
db.document(ref!.documentID).updateData([
“myDocumentId” : "\(ref!.documentID)"
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
}
}

Would be nice to find a cleaner way to do it but until then this works for me.

Unfortunately, this will not work:

let db = Firestore.firestore()


let documentID = db.collection(“myCollection”).addDocument(data: ["field": 0]).documentID


db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])

它不工作,因为第二个语句在 documentID 完成获取文档的 ID 之前执行。因此,在设置下一个文档之前,必须等待 documentID 完成加载:

let db = Firestore.firestore()


var documentRef: DocumentReference?


documentRef = db.collection(“myCollection”).addDocument(data: ["field": 0]) { error in
guard error == nil, let documentID = documentRef?.documentID else { return }


db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])
}

这不是最漂亮的,但这是唯一的方法来做你要求的。这个代码在 Swift 5里。

在省道中你可以使用:

`var itemRef = Firestore.instance.collection("user")
var doc = itemRef.document().documentID; // this is the id
await itemRef.document(doc).setData(data).then((val){
print("document Id ----------------------: $doc");
});`

在 Node

var id = db.collection("collection name").doc().id;

The simplest and updated (2022) method that is the right answer to the main question:

“是否有可能在添加之前获得 ID?”

v8:

    // Generate "locally" a new document in a collection
const document = yourFirestoreDb.collection('collectionName').doc();
    

// Get the new document Id
const documentUuid = document.id;
 

// Sets the new document with its uuid as property
const response = await document.set({
uuid: documentUuid,
...
});


V9:

    // Get the collection reference
const collectionRef = collection(yourFirestoreDb,'collectionName');


// Generate "locally" a new document for the given collection reference
const docRef = doc(collectionRef);


// Get the new document Id
const documentUuid = docRef.id;


//  Sets the new document with its uuid as property
await setDoc(docRef, { uuid: documentUuid, ... })

在 Python 上保存后获取 ID:

doc_ref = db.collection('promotions').add(data)
return doc_ref[1].id

对于 node.js 运行时

const documentRef = admin.firestore()
.collection("pets")
.doc()


await admin.firestore()
.collection("pets")
.doc(documentRef.id)
.set({ id: documentRef.id })

这将创建一个具有随机 ID 的新文档,然后将文档内容设置为

{ id: new_document_id }

希望这能解释清楚这是怎么回事

docs for generated id

我们可以在文档中看到 doc()方法。它们将生成新的 ID,并且只在此基础上创建新的 ID。然后使用 set()方法设置新的数据。

try
{
var generatedID = currentRef.doc();
var map = {'id': generatedID.id, 'name': 'New Data'};
currentRef.doc(generatedID.id).set(map);
}
catch(e)
{
print(e);
}

您可以使用一个 helper 方法来生成一个 Firestorish ID,然后调用 collection("name").doc(myID).set(dataObj)而不是 collection("name").add(dataObj)。如果 ID 不存在,Firebase 将自动创建文档。

助手方法:

/**
* generates a string, e.g. used as document ID
* @param {number} len length of random string, default with firebase is 20
* @return {string} a strich such as tyCiv5FpxRexG9JX4wjP
*/
function getDocumentId (len = 20): string {
const list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
let res = "";
for (let i = 0; i < len; i++) {
const rnd = Math.floor(Math.random() * list.length);
res = res + list.charAt(rnd);
}
return res;
}

Usage: const myId = getDocumentId().

9号火力点

doc(collection(this.afs, 'posts')).id;

对于新的 Firebase 9(2022年1月) ,我正在开发一个评论部分:

const commentsReference = await collection(database, 'yourCollection');
await addDoc(commentsReference, {
...comment,
id: doc(commentsReference).id,
date: firebase.firestore.Timestamp.fromDate(new Date())
});

Wrapping the collection reference (commentsReference) with the doc() provides an identifier (id)

如果您不知道当您需要 id 时集合将是什么:

这就是 Firestor 生成 id 所使用的代码:

const generateId = (): 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;
};

参考文献:

火还原: id 在集合中是唯一的还是全局的?

Https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#l36