简体   繁体   中英

Get snapshot of the document on success of saving it in google cloud firestore

I am testing the below code to create a new document and obtain a snapshot of it in order to retrieve the auto-generated the document id from the snapshot. When I log it, its coming out as undefined.

Can someone suggest a way to obtain the document id in a promise?

 db.collection("cities").doc().set({
        name: "Los Angeles",
        state: "CA",
        country: "USA"
    })
    .then(function(snapshot) {
        console.log("Document successfully written!" + snapshot);
    })
    .catch(function(error) {
        console.error("Error writing document: ", error);
    });

You can do as follows:

const docRef = db.collection("cities").doc();
const docId = docRef.id;

docRef.set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})
.then(function() { 
    console.log("Document successfully written!");
})
.catch(function(error) {...}
    

With the doc() method, "if no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference ".

Note that this is independent from the fact you use, or not, the DocumentReference to write to the database. In other words, the automatically-generated unique ID is generated in the client, not in the Firestore backend. And note that this is not an asynchronous operation, so no need "to obtain the document id in a promise".


Finally note that the set() method does not return a snapshot of the document (you titled your question with "Get snapshot of the document on success)" but a Promise<void> .

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