Firebase: Get document snapshot after creating

2019-08-18 19:25发布

I know that I can create a new query to read the doc by id in callback. But can I get the whole snapshot in the callback after creating document or at least TIMESTAMP?

firebase.firestore().collection("comments").add({
  body: data
})
.then(comment => {
  console.log(comment);
})
.catch(error => {
  console.log(error);
});

1条回答
▲ chillily
2楼-- · 2019-08-18 19:34

Calling CollectionRef.add(...) return a reference to the newly created document. To be able to access the data of that new document you'll need to still load it. So:

firebase.firestore().collection("48486654").add({
  timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function(docRef) {
  docRef.get().then(function(doc) {
    console.log(doc.data().timestamp.toString());
  });
})
.catch(function(error) {
  console.error(error);
});

For a working example, see: https://jsbin.com/xorucej/edit?js,console

查看更多
登录 后发表回答