Javascript 查询 Firestore 数据库以获取文档 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47876754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Query firestore database for document id
提问by Developer
I want to query a firestore database for document id. Currently I have the following code:
我想在 Firestore 数据库中查询文档 ID。目前我有以下代码:
db.collection('books').where('id', '==', 'fK3ddutEpD2qQqRMXNW5').get()
I don't get a result. But when I query for a different field it works:
我没有得到结果。但是当我查询不同的字段时,它可以工作:
db.collection('books').where('genre', '==', 'biography').get()
How is the name of the document id called?
文档id的名称是如何命名的?
回答by Denys Mikhalenko
I am a bit late, but there is actually a way to do this
我有点晚了,但实际上有一种方法可以做到这一点
db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()
This might be useful when you're dealing with firebase security rules and only want to query for the records you're allowed to access.
当您处理 firebase 安全规则并且只想查询您被允许访问的记录时,这可能很有用。
回答by Todd Kerpelman
Try this:
尝试这个:
db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()
(The first query is looking for an explicit user-set field called 'id', which probably isn't what you want.)
(第一个查询正在寻找一个名为“id”的显式用户集字段,这可能不是您想要的。)
回答by Venkat
You can get a document by its idfollowing this pattern:
您可以通过id以下模式获取文档:
firebase
.firestore()
.collection("Your collection")
.doc("documentId")
.get()
.then((docRef) => { console.log(docRef.data()) })
.catch((error) => { })
回答by John
From Firestore docsfor Get a document.
从Firestore 文档获取文档。
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

