How can I get back the documument ID after I set a new one?
I have a few attempts but here is my latest:
handleCreateCard = async (name, token) => {
try {
const new_card = await firestore()
.collection('Cards')
.doc()
.set({
user_id: user.uid,
name: name,
token: token,
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.then(() => this.props.navigation.navigate("CardDetail", {cardId: 2}));
// console.log("ATTEMPT !", handleCreateCard);
// console.log("ATTEMPT 2", new_card);
} catch (error) {
console.log(error.toString(error));
}
}
The docRef
line gets me the error:
Error: TypeError: null is not an object (evaluating 'docRef.id')
Logging handleCreateCard Error: ReferenceError: Can't find variable: handleCreateCard
Then the new_card
: "THIS IS HERE undefined"
Tried doing:
.then(docRef => {
console.log("Document written with ID: ", this.id); // also tried docRef.id
})
I get Document written with ID: undefined
with docRef.id: TypeError: null is not an object (evaluating 'docRef.id')
The document is being created as well so not sure why it's not coming back
I've tried a handful of ways to do this and then also tried everything in here which some is above: Firestore - How to get document id after adding a document to a collection
Not sure why it's not working.
Any help?
As described in the API documentation, doc() with no parameters returns a DocumentReference immediately which already contains the ID.
const docRef = await firestore()
.collection('Cards')
.doc()
const id = docRef.id
docRef
.set(...)
.then(/* use the id here if you want */)
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.