Delete a full document - javascript

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()

Related

Firestore is deleting the last document not the one I selected

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.

how to query from update handler javascript code

What I'm trying to do:
I want to add data (id, data) to db. While doing so, I want to check if the id already exists and if so, append to existing data. else add a new (id, data) entry.
Ex: This could be a db of student id and grades in multiple tests. If an id exists in the db already, I want to just append to the existing test scores already in db, else create a new entry: (id, grades)
I have setup an update handler function to do this. I understand, couchdb insert by default does not do the above. Now - how do I check the db for that id and if so, decide to whether to add a new entry or append. I know there is db.get(). However, I presume since the update handler function is already part of the db itelf, there may be a more efficient way of doing it.
I see this sample code in the couchdb wiki:
function(doc, req){
if (!doc){
if ('id' in req && req['id']){
// create new document
return [req, 'New Document'];
}
// change nothing in database
return [null, 'Incorrect data format'];
}
doc[id] = req;
return [doc, 'Edited World!'];
}
a few clarifications in this example that's not clear: where do we get the id from? Often the id is not explicitly passed in while adding to db.
Does that mean, we need to explicitly pass a field called "_id"?
how do I check the db for that id and if so, decide to whether to add a new entry or append.
CouchDB does this for you, assuming HTTP client triggers your update function using the ID. As the documentation describes:
When the request to an update handler includes a document ID in the URL, the server will provide the function with the most recent version of that document
In the sample code you found, the update function looks like function(doc, req) and so in the code inside of that function the variable doc will have the existing document already "inside" your CouchDB database. All the incoming data from the client/user will be found somewhere within req.
So for your case it might look something like:
function(doc, req){
if (doc) {
doc.grades.push(req.form.the_grade);
return [doc, "Added the grade to existing document"];
} else {
var newDoc = {_id:req.uuid, grades:[req.form.the_grade]};
return [newDoc, "Created new document ("+newDoc._id+") for the grade"];
}
}
If the client does a POST to /your_db/_design/your_ddoc/_update/your_update_function/existing_doc_id then the first part of the if (doc) will be triggered, since you will have gotten the existing document (pre-fetched for you) in the doc variable. If the client does a POST to just /your_db/_design/your_ddoc/_update/your_update_function, then there is no doc provided and you must create a new one (else clause).
Note that the client will need to know the ID to update an existing document. Either track it, look it up, or — if you must and understand the drawbacks — make them determinate based on something that is known.
Aside: the db.get() you mentioned is probably from a CouchDB HTTP client library and is not availble (and would not work) in the context of any update/show/list/etc. functions that are running sandboxed in the database "itself".
Cited from the documentation:
If you are updating an existing document, it should already have an _id set, and if you are creating a new document, make sure to set its _id to something, either generated based on the input or the req.uuid provided. The second element is the response that will be sent back to the caller.
So tl;dr, if the _id is not specified, use req.uuid.
Documentation link: http://docs.couchdb.org/en/stable/ddocs/ddocs.html#update-functions

Cloud FireStore: Retrieve 1 document with query

I'm trying to retrieve a single document from a collection. I'm now using the code below that returns a collections of items, but I know that there is only one item. So it ain't that clean.
Setup:
private db: AngularFirestore
private itemSubs: Subscription[] = [];
itemAd= new Subject<Item>();
fetchItemFromDatabase(itemId: string) {
this.itemSubs.push(
this.db.collection('items', id => id.where('itemId', '==', itemId)).valueChanges().subscribe((items: Item[]) => {
this.itemAd.next(items);
}));
}
I tried to do it with this.db.collection('items').doc(itemId).get() , but I'm getting an error on get() that it's not found/supported. I also didn't got autocompletion when trying to call this methode (methode found in the official cloud firestore documents).
I looked at around at some other solutions and then tried it with this.db.collection('items').doc(itemId).ref.get().then(...) , but here I got an empty doc back.
So I'm a bit stuck at the moment and I don't want to use that whole collections logic when I know there is only 1 item in it.
There may be multiple documents with itemId equal to a given value. While you may know that there is only one in your app, the database and API cannot know nor enforce that. For that reason the query you run will always return a query snapshot that potentially contains multiple documents.
this.db.collection('items', id => id.where('itemId', '==', itemId))
If you want to enforce that there is only one document with the given item ID, consider using that item ID as the document name instead of storing it as a field in the document.
There can be only one document with a given name, so that means the ID is guaranteed to be unique. And you can then retrieve that document with:
this.db.collection('items').doc(itemId)

Meteor event for subscriber of collection for new insert of document in mongodb

I have a question regarding when a new document is added to mongodb
I have an order object that can be added server side after a meteor method call.
I have an admin page called ‘incomingOrders' subscribing to all orders.
What i would like to do , is just play a sound when on this page , when a new order is inserted into the database.
my client side collection updates with the new order, but i need it to show some sort of alert (i.e. alert box, sound , flashing screen!!!)
How would i exactly do this?
is there an event that can that is triggerd when a new document is inserted that i can subscribe to?
I have no code tested as i don’t have any idea how to do it.
So i found the answer to my question
I used the cursor.observe function to observer when a document is added to my collection.
Template['incomingOrders'].helpers({
orders:function(){
var cursor = Orders.find({},{sort: {createdAt: -1}});
// watch the cursor for changes
var handle = cursor.observe({
added:function(order){
if(!initializing){
console.log('order from handle');
console.log(order);
document.getElementById('xyz').play();
}
}
});
return cursor;
}
});
I have an initialising check (which is set to false in the rendered function of the template) as this function seems to be called on every element while the template is rendering . And then i simply call play on an audio element to alert me of a new document being added.
If there is a better way , please inform me!

Why doesn't add event be triggered when Collection fetch successfully?

var documents = new Backbone.Collection();
documents.url = "/documents";
documents.bind("add", function(doc){
console.log(doc);
});
documents.fetch();
Why doesn't the add event triggered when the fetch function gets the array of models successfully?
What documentation says:
When the model data returns from the server, the collection will reset ...
If you'd like to add the incoming models to the current collection, instead of replacing the collection's contents, pass {add: true} as an option to fetch.
So the answer to your question: call fetch like this
documents.fetch({add: true});
And it will work fine.
I think the event add is fired after you add elements to an already populated Collection.
In this specific case you can listen to the reset event instead of add. Also remember to verify that your collection it's getting data at all.

Categories

Resources