Google cloud firestore 如何在Firestore中检索添加的文档数据?
我有这样的代码,可以从中获取新插入的文档id:Google cloud firestore 如何在Firestore中检索添加的文档数据?,google-cloud-firestore,Google Cloud Firestore,我有这样的代码,可以从中获取新插入的文档id: db.collection("cities").add({ name: "Tokyo", country: "Japan" }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", e
db.collection("cities").add({
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
可以从ref获取数据吗?是的,您可以这样做:
.then(function(docRef) {
db.collection("cities").doc(docRef.id).get()
.then(snap => {
console.log('Here is the document you wrote to', snap.data()
})
})
当然,它需要另一次阅读,而你可能不想阅读。我找到了解决方案
static async createUserPofile(uid) {
const db = Firebase.firestore(),
date = Firebase.firestore.FieldValue.serverTimestamp(),
data ={
user_id: uid,
creation_time: date,
update_time: date
},
docRef = await db.collection("user_profiles").add(data),
get = await docRef.get();
return get.data();
}
这回答了你的问题吗?是的,没错。下面@GrantSingleton的回答表达了在add之后获得的想法。为什么不接受呢?另外,我看不到通过获取和返回
.data()
得到了什么。你不是已经在上面一行有data={…}
了吗?啊,我明白了。很抱歉我希望add会返回一个服务器时间戳。我认为要求整个对象按所写的方式运行太过分了,因为在add之后运行的触发器可能会改变它。不管怎么说,我对首先给出的正确答案的本质投了赞成票。