How do I delete a data that contains spaces in Firebase Database? - firebase

I have managed to delete a data in the firebase data base using this code, but it won't delete any data that contains spaces for example I tried to delete a data that is called "Test" it was deleted, but I have a data called "Test 1" but it won't get deleted, also some of the other data won't get deleted.
DeleteData1.addEventListener('click',(e)=>{
var deleteCrop1 = document.getElementById('deleteCrop').value;
remove(ref(database, 'Crops/' + document.getElementById('deleteCrop').value))
.then(()=>{
alert("Crop successfully deleted");
})
.catch((error)=>{
alert("Unsuccessful, error" + error);
})
});

Related

Error : "No document to update " in Firestore

Im using cloudFirestore as the database and i want to update a Field that lives in a document.
collection :users.
document:user.
field:website.
so for that i did like so :
db.doc('/users/user').update({website:'user.com'});
but iam getting this Error :
No document to update: projects/social-app-12282/databases/(default)/documents/users/user'
Can someone tell me wht this happen,thank you in advance
Edit:
you can see here that i have a docment called user
For you to update a document in Firestore, the structure of the update is a little bit different in relation to yours. As per the documentation - accessible here - you need to select the collection and then, the document you want to update. The code would be something like the below one:
var usersRef = db.collection("users").doc("user");
// Set the "user" field of the city 'DC'
return usersRef.update({
"website": "user.com"
})
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
A simplified version would be:
db.collection("users").doc("user").update({
"website": "user.com"
})
.then(function() {
console.log("Document successfully updated!");
});
While this is untested code, I believe it should help you with understanding on how to update the values and as a starting point. You can get more examples from the official documentation as well.

How to fetch data from firestore documents from a collection and store in the list

I have a list of a document ids and I want to fetch the data of those documents from Firestore and display it using the FutureBuilder.
contestList = [awebnmsdfjkeeer23,324cdas4asdf, 34sdfasgadsg]
Future<void> fetchUsergameData() async {
contestList.forEach((element) async{
await Firestore.instance.collection('LiveGames').document('$element')
.get().then((dss) {
if(dss.exists) {
tempgame.add(dss.data["GameData"]);
temproom.add(dss.data["Room"]);
temptitle.add(dss.data["Title"]);
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
}
}).then((value) => {});
});
print(joinedContests);
}
}
I have used the above function to get the data and try to store in the list, like one document data in list. But i am getting the blank list of the data. How to get the whole document and display it using the FutureBuilder in flutter
It looks like you have multiple different issues on your code:
contestList has invalid keywords. 324cdas4asdf and 34sdfasgadsg are not valid variable names as they both start with a number, which is not a valid variable name. If they are supposed to be the ids that you want to retrieve they must be enclosed by ", which will make them strings.
You are trying to access the document using '$element' as if it were a bash variable, but there are two problems there: it's not done like that and there no need to do it. element already holds the value as a string so it just has to be accessed as is.
You are calling the method then twice without doing anything the second time. This shouldn't be a concern, but it simply doesn't do anything and can me omitted.
Below you will see an edited version of your code fixing all the aforementioned mistakes.
contestList = ["awebnmsdfjkeeer23", "324cdas4asdf", "34sdfasgadsg"]
Future<void> fetchUsergameData() async {
contestList.forEach((element) async{
await Firestore.instance.collection('LiveGames').document(element)
.get().then((dss) {
if(dss.exists) {
tempgame.add(dss.data["GameData"]);
temproom.add(dss.data["Room"]);
temptitle.add(dss.data["Title"]);
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
}
});
});
print(joinedContests);
}
}
On another note, it's unknown to us the type of tempgame, temproom and temptitle but judging by how you are accessing it you may simply want to do something like this:
tempgame = dss.data["GameData"];
temproom = dss.data["Room"];
temptitle = dss.data["Title"];
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);

Firebase updating or deleting array of objects in a vue js app

In my Vue js application i am pushing data from firebase firestore collection in an array in the form of objects , to display in a table
export default{
created(){
const thisIns= this
let user = firebase.auth().currentUser
let Ref = firebase.firestore().collection('College')
Ref.get().then(snapshot=>{
snapshot.forEach(doc=>{
let id = doc.id
Ref.doc(id).collection('Students').onSnapshot(function(snapshot){
snapshot.docChanges().forEach(function(change){
if(change.type==="added"){
let obj = change.doc.data()
thisIns.students.push(obj)
})
})
})
})
}
this students array is then displayed in a table . Now the problem is whenever an update is made in a document containing student information , instead of changing the data in the array it pushes the same document containing the updated values in the students array thus there is same student more than once , one with previous details and one with the updated details , this is corrected only when the page is refreshed , same when any student document is deleted the page needs to be refreshed for deletion from the table/array. How can the updation / deletion be done without reloading the page so that the application does not increase number of reads ?

Why are non auto-generated document Ids are in italics in Firestore console?

When i add a document with my own document Id (not auto generated), document Id node is in italics as shown in the screenshot from Firestore console. What is the reason behind this?
My code to add data is
const billingRef = db
.collection('billing/test/2017/months/11')
.doc();
billingRef
.set({ name: 'ABC' })
.then(_ => {
console.log('saved');
})
.catch(err => {
console.log(err);
});
Above code adds a node successfully, but adds node "test" and "months" in italics.
screenshot 1
screenshot 2
screenshot 3
My query yields zero results for such records in firestore, following code. How can I query all the nodes under billing?
db.collection("billing").get().then(function(querySnapshot) {
console.log(querySnapshot.size) // this is always 0
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
});
Following up on my comment above you will see in the Firestore console that for Documents in italic there is a small text saying "This document does not exist, it will not appear in queries or snapshots", for non-italic it says "This document has no data", so the intuition is that when the Document is created in code without any Fields then it is "null" (a subcollection does not count). If a Field is added and removed, then the Document is simply empty and not null.
Since your query for the Documents under billing are in italic ("null" or does not exist), as the text above states, they will not appear in queries.
The solution would be to either add the document through the Firestore console because here Documents are created as empty, or if in code, add a Field and maybe remove it again if not needed, then the Documents will appear in queries.
The problem, I later came to find from this Question's answer for me was creating a sub collection to an empty document. This was my code that was bringing up grayed out documents.
db.collection('temporal')
.doc('documentexample')
.collection("files")
.add({
name: "Lorem"
})
.catch((error) => {
console.error("Error adding file: ", error);
});
In the above code the doc documentexample had no field in it. So the code goes ahead and creates documentexample (it has no fields) then creates a subCollection in it files. This according to firebase just grays out the first document documentexample.
The workaround to this is first create the document add a field in it then create a subcollection to it and on and on... For my use-case, I created a function that creates the document and adds a field to it when the user signs up for the first time

Firebase Google cloud Function - Database Trigger - How to delete extra records & files programmatically

Use case:
Users can upload images using UI (mobile, web). Firebase storage and insertion of database record for the file is done in UI. Users can upload a set number of files say for testing max 5. Solution is achieved through Firebase Storage to store files and Firebase Database to track the URLs of the image for future use in other screens.
I have a google cloud function that gets triggered when a user uploads an image in frontend to firebase storage. Once the file is uploaded I create a firebase database record under the uid. the google cloud function triggers onCreate().
Structure of Database
Users/{uid}/images/
{ name: file1.jpg, date_created: "2017-11-01", downloadURL : "//...."}
For every record creation I check the count of records under uid/images node and check if the snapshot is greater than MAX_LIMIT. If it is greater than MAX_LIMIT I attempt to remove the record from the database and in another GCF (listening to .onDelete() Trigger) I delete the firebase storage file.
The issue is Once the record count gets more than MAX_LIMIT... the snapshot behaves strange. It iteratively deletes all the records thus triggering GCF Delete function and removing all files from storage.
No issues with GCF delete function for storage.. it works charm... and removes all files from storage due to the code behavior in GCF onCreate DB function.
To keep short putting below just the function that is logic trouble.
//var database = admin.database(); passed to function
exports.handler = function(event, database, esClient)
{
var usersRef = database.ref('users');
console.log('inside Backend Function1 -
checkImageCounterFunction');
console.log( 'event data =' + JSON.stringify(event.data.val()) );
console.log('event data length =' + event.data.numChildren());
console.log('event.params.uid =' + event.params.uid );
var objLength = 0;
usersRef.child(event.params.uid+'/images').once('value',
function(snapshot) {
console.log('Count: ' + snapshot.numChildren());
objLength = snapshot.numChildren();
console.log('database ref length =' + objLength);
if(objLength > 0) {
if(objLength > serverConfig.max_image_counter){
console.log('Maximum number of images upload found.
Deleting old images and records.');
var readDBPromise = new Promise(function (resolve, reject)
{
usersRef.child(event.params.uid+'/images')
.orderByChild('date_created')
.limitToFirst(objLength - serverConfig.max_image_counter)
.on("value", function(snapshot) {
console.log('snapshot.val()
=>'+JSON.stringify(snapshot.val()) );
snapshot.forEach(function(data) {
console.log('snapshot.for.data value
='+JSON.stringify(data) );
console.log('item Key = ' + data.key + ' val ='+
JSON.stringify(data.val()));
usersRef.child(event.params.uid+'/images/'+data.key)
.remove(function (error) {
if (!error)
console.log('Success - Firebase Database remove
{'+data.val().name+'}');
else
console.log('Error - Firebase Database remove
{'+data.val().name+'}');
});
});
resolve();
});
});
readDBPromise.then(function (result){
console.log('Returning from function!');
usersRef.child(event.params.uid+'/image_counter')
.set(serverConfig.max_image_counter);
return;
});
} //end if objLength > MAX
else
return usersRef.child(event.params.uid+'/image_counter')
.set(objLength);
}
else
console.log('objLength is 0 or negative = '+objLength);
return;
});
//return;
};
From Bob Snyder's comment
The query, set, and remove operations you are performing are asynchronous and return a Promise. You need to chain them together and return a Promise as the result of the Cloud Function trigger. It doesn't appear you are doing that

Resources