Firestore is deleting the last document not the one I selected - javascript

I am trying to impelement a delete function in Firestore database and the problem is that when I click delete, it deletes the last document created, not the one that I want to delete.
This is how I get the data from the database:
db.collection("flights").get().then((snapshot) =>{
snapshot.docs.forEach(doc => {
var data = doc.data();
var docID = doc.id;
And this is how I am trying to delete it:
function deleteFlight(docID){
firebase.firestore()
.collection("flights")
.doc(docID)
.delete()
.then(() => console.log("Document deleted")) // Document deleted
.catch((error) => console.error("Error deleting document", error));
}
I want to specify that after I create a new document, the website is refreshed, so I think it loses somehow the document id.

In the comment section you have specified that you are calling the deleteFlight() function from a html button. As you are using forEach() loop after getting the collection of documents and within that populating docID, by the time the html button is clicked the forEach() loop would have been completed and then docID will have the document id of the document which comes last in ascending order because by default the documents are sorted in ascending order of document id as mentioned in this document. In your case I suspect the document id for the recently added document comes last when sorted in ascending order. This is the reason the recently added document is getting deleted.
I am not sure of your use case. But I would suggest you to declare a variable outside of the db.collection() method and implement some logic according to your use case to populate it with the document id which you want to delete. Then use that variable in the deleteFlight() function.

Related

Why collection.get() is not working in Firestore?

I'm working with the following collection and sub-collections in Firestore.
I need to retrieve the list of the documents inside "Schedine", but the following code returns nothing.
const ref1 = await firestore.collection("Schedine").get();
ref1.forEach(doc => {
console.log(doc.id);
});
// expected output: gx8qiytV8Zgs0AJR4swFqTH3T82 , but nothing shown
Instead, if I try to get() the documents inside "in corso", a sub-collection of a document inside "Schedine", it works, with the exact same code:
const ref2 = await firestore.collection("Schedine").doc("gx8qiytV8Zgs0AJR4swFqTH3T822").collection("in corso").get();
ref2.forEach(doc => {
console.log(doc.id);
});
// WORKING
How could I get the list of the documents inside "Schedine"?
If you look carefully, you'll see that the document ID in your screenshot is shown in italics. This means that there's no document gx8qiytV8Zgs0AJR4swFqTH3T822 inside your Schedine collection, and the console just shows that ID so that it can show you the subcollections under it.
Since there's no documents in Schedine, calling get on that collection returns an empty query snapshot. But the path exists, which is why you can access the subcollection once you know the document ID in your second snippet.
There's no API on the collection reference to get such non-existent entities, so the common solution is to create an (empty) document when you also create the subcollection.

delete a collection with document and collection again inside (firestore react native)

I am having trouble deleting on firestore
here's my delete
var chatId = route.params.number; // +639266825843
var docRef = firestore().collection('ChatRoom').doc(chatId).collection('messages');
docRef.doc(chatId).delete();
but everytime i try to delete nothing happens . There's no error at all .
this is how I set that collection
firestore().collection('ChatRoom')
.doc(id)
.collection('messages')
.add({...myMsg, createdAt:firestore.FieldValue.serverTimestamp()})
If you want to delete all the docs of the messages (sub)collection, you need to query the collection and delete each document, for example by using Promise.all() or by using a batched write (containing only deletions)
var chatId = route.params.number; // +639266825843
var colRef = firestore()
.collection('ChatRoom')
.doc(chatId)
.collection('messages');
colRef.get().then((querySnapshot) => {
Promise.all(querySnapshot.docs.map((d) => d.ref.delete()));
});
The docs property of the QuerySnapshot returns an array of QueryDocumentSnapshots.
In addition, look at how your +639266825843 document is displayed in an italic font: this means, in the console, that this document is only present as "container" of one or more sub-collection(s) but that it is not a "genuine" document. It does not exist, because you never created it, you only created docs in one of its subcollections. More detail here.

How to order document .add() data in firestore in Javascript

Ive been struggling with ordering the documents in Cloud Firestore.
Im using the collection.add() method. And reading the data and displaying it on the screen.
Heres how i write it into the database:
let shared = {
category : category,
username : user.displayName,
createdAt : date,
}
// Add a new document with a generated id.
const sharedRef = db.collection('shared');
sharedRef.orderBy('createdAt', "desc");
sharedRef.add(shared)
.then(function() {
console.log("Saved to database");
}).catch(function(error) {
console.error("Error adding document: ", error);
});
And to Read the data I just use doc.data forEach.
I Read the data with doc.data() forEach
Is there anyway i can order the shared documents by the date created?
orderBy is for queries that read data, not for adding data. You can't set the order at the time you call add(). The order you see in the console by default is always going to sort by the document ID, which is random for every call to add().
You shouldn't be concerned about the order that the documents appear in the console. You should only be concerned about putting fields in each document that you can use later to sort them in a query.

SnapshotChanges subscription doesn't detect final deletion of sub-collection item

I have the following code to retrieve some user information from Cloud Firestore - it grabs the list of challenges a user is part of from a subcollection on their user document and then uses those ids to collect the full challenge information from the top level challenge document.
When I delete a challenge I remove it from the main challenges document and then remove the id reference in each users challenges subcollection. The UI updates nicely for each delete as snapshotchanges is an active subscription, until I delete the final one. The final one deletes from the database but stays in the UI until I refresh or make a new challenge.
My theory is that becuase deleting the last document in the challenges subcollection also deletes the subcollection this means snapshotChanges doesn't run as there is no longer a collection in the database to monitor the changes on.
Any thoughts on how to workaround this would be great.
getChallenges() {
return this.getCurrentUserId().pipe(switchMap(userId => {
return this.db.collection(`users/${userId}/challenges`).snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
console.log('in get challenges: ', data);
const user_challenge_key = a.payload.doc.id;
return this.getOneChallenge(data['id'], user_challenge_key);
}))
);
}));
}
getOneChallenge(id, user_challenge_key = null): Observable<Challenge> {
return this.db.doc(`challenges/${id}`).snapshotChanges().pipe(
take(1),
map(changes => {
const data = new Challenge(changes.payload.data());
const challengeId = changes.payload.id;
data.user_challenge_key = user_challenge_key;
data.id = id;
console.log('in get One challenge: ', data);
return data;
})
);
}
Maybe maintain a dummy document in order to keep the sub-collection
For example, validate if you going to delete the last element of that sub-collection add the dummy and later delete the last element
for the first insertion check if the dummy object is the only document, after that add your first entry and delete the dummy
I found a similar question with similar approach on the Firestore's Google Group

Delete a full document

I'm trying to delete a full document in a collection.
I have a collection called "pushes", every document inside gets an auto generate id from firebase.
I use this code to listen to create event of pushes:
functions.firestore.document('pushes/{msgId}').onCreate(ev => {
});
Everything works well I send my push but I want to delete this request.
I tried this code:
admin.firestore().doc('pushes/'+querySnapshot.id)).delete();
Still doesn't work, I tried also to use the "where" query but I don't know the auto document id key to compare:
admin.firestore().collection('pushes').where('<WHAT HERE?????>', '==', id).get().delete()

Categories

Resources