Firebase await error: Some requested document was not found - firebase

async function confirmCode() {
try {
data = await confirm.confirm(code);
if(data.additionalUserInfo.isNewUser){
await firestore.collection("Users").doc(auth.currentUser.uid).update({
id:auth.currentUser.uid,
})
}
} catch (error) {
console.log(error)
}
//Error: [firestore/not-found] Some requested document was not found.
When I use this code to create user & also make firestore data of user it returns error.
But if user is already created, this returns wonderful result.
Any helps can I get to successfully create firestore data when new user comes?

From the error message //Error: [firestore/not-found] Some requested document was not found. is seems that you have a problem with the Firestore document you try to update with await firestore.collection("Users").doc(auth.currentUser.uid).update();
One classical problem when using auth.currentUser is that it is possible that the Auth object is not fully initialized and that auth.currentUser.uid is therefore null. As explained in the doc you should either use the onAuthStateChanged() observer or check that auth.currentUser is not null.
It may also happen that the document is not existing for another reason (e.g. you never created it!): since you are calling update() the document must exist, see the doc: "The update will fail if applied to a document that does not exist.".

Related

How to create a document if the document doesn't exist or else don't do anything?

I Wanted To Ask If It Is Possible To Make A New Document With A UID If It DOESN'T Exist But if it exists NOT To Do Anything (and if possible return an error) In Firestore. (In Modular Javascript)
And If It Is Possible How?
Note: I Already Read This Question:StackOverFlow 46888701 But It Doesn't Fit My Requirements because after creating the document I want to be able to update it too.
Edit: I Wanted To Know Without Using getDoc because when i use it acts like a read and i don't want to spend lots of my no of reads from my limit.
You should first try to get the document and check if it exists then proceed to your document set/update. See sample code below:
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "<collection>", "<UID>");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document exist!");
// Throws an error.
throw new Error('Document Exist!');
} else {
await setDoc(docRef, {
// Document Data
});
}
For more relevant information, check out these documentations:
Get a document
Update a document
Set a document
Edit:
If you don' t want to use getDoc then you have the option to use updateDoc, it will produce an error but you can still execute a setDoc method on the catch method. On this approach, you're doing a fail-safe practice that you're responding in the event of failure. See code below:
const docRef = doc(db, "<collection>", "<UID>");
// Produces error log if no document to update
updateDoc(docRef, {
// document data
})
.catch((error) => {
// console.log(error);
setDoc(docRef, {
// document data
});
});
According to the documentation, an update is just a write operation:
Charges for writes and deletes are straightforward. For writes, each set or update operation counts a single write.
We have established that an update is just a write operation (there's no reading involved). A write is a change in a document, since you're not changing anything because the document didn't exist then you won't be charged at all.
In web version 9, the function that can help you create a document is named setDoc(), which creates or overwrites a document at a specific document reference.
How to create a document if the document doesn't exist or else don't do anything?
If you want to achieve that, you have to check if the document already exists. If it doesn't exist, create it using setDoc(), otherwise, take no action, but do not use the updateDoc() function in this case.
Remember that the updateDoc() function helps only when you want to update some fields of a document without overwriting the entire document. If the document doesn't exist, the update operation will fail.
Edit:
According to your edited question, please note that there is no way you can know if a document exists, without checking it explicitly. You can indeed not do that check, but you'll end up overwriting the document over and over again. Please also note, that a write operation is more expensive than a read operation. So that's the best option that you have.

Firebase DocumentReference.update is deleting the document

I have flutter code that I have been using for a while that I use to perform crud operations on my firestore documents. I have one situation where an update appears to be deleting a document. I have put a breakpoint in my code just before the update and hold a reference to the document in the firestore console. As soon as the update runs, the document is removed from firestore. Does this make sense? Is there any condition that would cause a document to be deleted when invoking a DocumentReference.update? Here is a snippet of my code showing the update I am trying to perform:
Future<void> updateInMyCartIndicator(
ShoppingListItem shoppingListItem) async {
logger.d("FSShoppingListItemHelper:updateInMyCartIndicator - ENTRY");
try {
CollectionReference shoppingListItemCollection =
FirebaseFirestore.instance.collection('shopping_list_items');
QuerySnapshot shoppingListQuery = await shoppingListItemCollection
.where("id", isEqualTo: shoppingListItem.id)
.get();
final DocumentReference docRefShoppingListItem =
shoppingListItemCollection.doc(shoppingListQuery.docs[0].id);
await docRefShoppingListItem
.update({'in_my_cart': shoppingListItem.inMyCart});
logger.d(
"FSShoppingListItemHelper:updateInMyCartIndicator - Update complete");
} catch (e) {
logger.d("FSShoppingListItemHelper:updateInMyCartIndicator - Exception");
print(e.toString());
}
}
I have tried to reproduce this behavior and no matter how did I update a document (empty HashMap as argument, null fields, etc..) it was not getting deleted. As such the most likely scenario is that the document gets deleted somewhere else in your code, probably as an unintended side effect.
Thanks for the response. I was able to get past this. Honestly, all I did was kill the simulator and my ide and the deleting stopped. I can’t explain why it was happening, but it has gone away.

cloud function trigger on create document

I need to create a firebase cloud function that will trigger every time I added a document to the collection. This the function:
exports.sendEmailConfirmation = functions.firestore.document('multies/{id}/tenties/{id}').onCreate((snap, context) => {
// Get an object representing the document
//...
return transporter.sendMail(mailOptions).catch((err) => {
console.error(err);
return {
error: err
}
});
});
I'm getting the following error in the console:
functions[sendEmailConfirmation(us-central1)]: Deployment error.
Failed to configure trigger providers/cloud.firestore/eventTypes/document.create#firestore.googleapis.com (gcf.us-central1.sendEmailApplicationConfirmation)
In the Firestore database I have a collection 'multies' that have multiple documents and foreach document I have a 'tenties' collection that could have multiple documents too. My function should trigger every time we add a document to the 'tenties' collection in any document in the 'multies' collection.
Can I get any help on how I'm configuring the path or what other error I'm having here?
I think you shouldn't have duplicated wildcards in your path:
try 'multies/{multiId}/tenties/{tentiId}' instead of 'multies/{id}/tenties/{id}'
Keep in mind that they will be available in your context.params object.

Firebase, add unique id and data - promise error add/set is not a function

How can I add document data as well as a unique id?
I am using:
if (fcmToken) {
firebase
.firestore()
.collection("users")
.add(fcmToken)
.set({
year
})
.then(function() {
return true;
})
.catch(function(error) {
return false;
});
}
I get the error:
Possible Unhandled Promise Rejection (id: 0):
TypeError: _reactNativeFirebase.default.firestore(...).collection(...).add(...).set is not a function
Chaining set after add doesn't really make any sense. The are independent operations, and both return a promise that resolves after the work is complete. The error you're seeing is telling that the promise returned by add doesn't have a method called set.
Just use one or the other, not both.
Using add, you can specify the entire document's content with the object you pass to it, and it will be assigned a random unique ID.
If you want to generate your own ID, build a DocumentReference to the document you want to create, and set it directly. For example:
firebase.firestore().collection("users").doc(fcmToken).set(...)
Use add instead of set. It will return the generated id.
https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference.html?authuser=0#add

Firestore query only needed fields (Firebase) [duplicate]

Here is my data structure:
I have an ios app that is attempting to access data from Cloud Firestore. I have been successful in retrieving full documents and querying for documents. However I need to access specific fields from specific documents. How would I make a call that retrieves me just the value of one field from Firestore in swift? Any Help would be appreciated.
There is no API that fetches just a single field from a document with any of the web or mobile client SDKs. Entire documents are always fetched when you use getDocument(). This implies that there is also no way to use security rules to protect a single field in a document differently than the others.
If you are trying to minimize the amount of data that comes across the wire, you can put that lone field in its own document in a subcollection of the main doc, and you can request that one document individually.
See also this thread of discussion.
It is possible with server SDKs using methods like select(), but you would obviously need to be writing code on a backend and calling that from your client app.
This is actually quite simple and very much achievable using the built in firebase api.
let docRef = db.collection("users").document(name)
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let property = document.get(field)
} else {
print("Document does not exist in cache")
}
}
There is actually a way, use this sample code provided by Firebase itself
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let property = document.get('fieldname')
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
I guess I'm late but after some extensive research, there is a way in which we can fetch specific fields from firestore. We can use the select keyword, your query would be somthing like (I'm using a collection for a generalized approach):
const result = await firebase.database().collection('Users').select('name').get();
Where we can access the result.docs to further retrieved the returned filtered result. Thanks!
//this is code for javascript
var docRef = db.collection("users").doc("ID");
docRef.get().then(function(doc) {
if (doc.exists) {
//gives full object of user
console.log("Document data:", doc.data());
//gives specific field
var name=doc.get('name');
console.log(name);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

Resources