简体   繁体   中英

How to get document by ID after insertion?

The idea is simple. User is adding a new document to collection and then wants to see it listed on the page without refreshing. I know I can sync all the dicuments with onSnapshot but that is kind of a huge deal, right now I simply want to get the inserted document by ID .

 addWish = function() { let wish = document.getElementById("wish-text").value; if (wish && this.checkSignedIn()) { this.database.collection("wishes").add({ wish: wish, author: this.user.name, date: 0 - Date.now(), voteup: 1, votedown: 0 }).then(function(docRef) { console.log("Document written with ID: ", docRef.id); this.database.collection('wishes').doc(docRef.id).get().then(function (documentSnapshots) { this.renderWishes(documentSnapshots, 1); }.bind(this)).catch(function(error) { console.error("Error getting document: ", error); }); }.bind(this)).catch(function(error) { console.error("Error adding document: ", error); }); 

Function renderWishes fails on one of the first lines. And then everything else fails too, for example foreach :

renderWishes = function(querySnapshot, type) {
    console.log(querySnapshot.docs[0].data());
    querySnapshot.forEach(function(doc) {
        let id = doc.id;
        doc = doc.data(); //and after I simply display data with templates ${doc.author}

Error getting document: TypeError: Cannot read property '0' of undefined

And

foreach`: "firebase.js:131 Error getting document: TypeError: querySnapshot.forEach is not a function

Is there any chance to fix this? Or it is impossible to get document by ID from Firestore?

The result of the async get() operation is returning an object that's different than what you're anticipating in your code.

In your code, you're putting the following object into a new document:

    {
        wish: wish,
        author: this.user.name,
        date: 0 - Date.now(),
        voteup: 1,
        votedown: 0
    }

When you get() that document immediately after the add(), the variable you call querySnapshot is going to contain a DocumentSnapshot with exactly those contents in return. DocumentSnapshot does not have a docs property, as you're trying to access. That why you're getting an error about it being undefined. DocumentSnapshot has an id property that will give you the id of the document you just fetched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM