Delete a array element from a Firestore database - javascript

I'm trying to delete an element from an array in a Firestore document. However, none of the approaches I tried had worked so far. My last attempt was like this:
const ref = firestore().collection('events').doc(extraid);
ref.get().then(document => {
const thing = document.data();
const rejected = thing.rejected || [];
const interested = thing.interested || [];
const fieldIndex = interested.findIndex(obj => obj.interestedId === sender);
const fieldToDelete = interested[fieldIndex];
firebase.firestore.FieldValue(fieldToDelete);
firebase.firestore.FieldValue.delete(fieldToDelete);
});
How can I delete an element from an array in a Firestore document?

You will have to update() the modified array field back to the document as suggested by the documentation. Calling FieldValue.delete() isn't enough - that just creates a FieldValue token that you can pass to update() to make the change. It will look something like this:
ref.update('interested', FieldValue.delete(fieldToDelete))

Related

How to use cloud function trigger based on two collections documents

I have a collection ReferalCodes in which each document is specified has these values where 'mine' value is false 'msg' value is false and mycode is user referal codes.
appliedcode: ""
mine:false
msg:false
mycode:"ASDF4G"
referals : []
And User has one more collection UserTransaction which have a field 'CountTrans' which is initialized as 0 when this value is 1 i want to trigger a function to check value of mine and appliedcode if the value of mine is true then and applied code have value of length 6 then i want to update the UserTransaction of that user and the appliedcode is referal code of some another user want to change UserTransaction of that user also
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { user } = require('firebase-functions/lib/providers/auth');
admin.initializeApp();
const db = admin.firestore();
exports.getCount= functions.firestore
.document('UserTransactions/{id}')
.onUpdate((change, context) => {
const newTransdata = change.after.data();
const previousTransData = change.before.data();
const docid = context.params.docid;
if(newTransdata.CountTrans === 1) {
const referalData = await
admin.firestore.collection('ReferalCodes').doc(docid).get()
const mine = referalData.mine;
const appliedCode = referalData.appliedCode;
let codes = [];
var myfrindid;
if(mine === true && appliedCode !== null) {
const friendData = await
admin.firestore.collection('ReferalCodes').doc('codes').get();
var referalcodes = friendData['ReferalCodes'];
referalcodes.forEach((items) =>{
if (items['code'] == appliedCode) {
myfrindid = items['id'];
}
});
await
admin.firestore.collection('ReferalCodes').doc(docid).update({
msg: true
})
}else{
}
}
});
Consulting the official documents is explained how to handle events on your database and trigger some different kind of triggers depending on your needs, for example:
onWrite(), which triggers when data is created, updated, or deleted in Realtime Database.
onCreate(), which triggers when new data is created in Realtime Database
onUpdate(), which triggers when data is updated in Realtime Database
onDelete(), which triggers when data is deleted from Realtime Database
For example, the first argument passed your onUpdate handler function is a Change object, this object has two properties, before and after, both DataSnapshot objects. These DataSnapshot objects describe the contents of the database before and after the change that triggered the function.
exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
const before = change.before // DataSnapshot before the change
const after = change.after // DataSnapshot after the change
})

receive specific data from Firebase with if statement in React Native

I am new with Firebase and React Native. I have created a database and now that when a certain number is equal to a number in 1 of the objects in firebase, it stores this data in an array.
I have the following code for that:
scanOutput = '0';
getUserData = () => {
console.log(this.scanOutput);
let ref = firebase.database().ref('Questions/1R1/NL');
ref.on('value' , snapshot =>{
var state = snapshot.val();
console.log(state);
if('1' === this.scanOutput){
this.setState({questions: state});
}
})
}
componentDidMount(){
this.scanOutput = this.props.navigation.getParam('output');
this.getUserData();
}
the database looks like this:
Currently the if statement contains a "1" hardcoded, what I want to achieve is that when this.scanOutput (in this case "1") equals "question_number" from the database, it places all data in the state.
Your code is reading all data under Questions/1R1/NL. Since there may be multiple questions under there, the snapshot may contain multiple child nodes. Your callback needs to handle those by looping over snapshot.forEach.
Something like this:
let ref = firebase.database().ref('Questions/1R1/NL');
ref.on('value' , snapshot =>{
snapshot.forEach((question) => {
var state = question.val();
if(state.question_number === this.scanOutput){
this.setState({questions: state});
}
})
})
If snapshot returns you an object then you can destructure it:
const { question_number } = snapshot.val();
console.log(question_number);
then you can have a check like:
if(question_number === this.scanOutput){

How can I `put` new values in an already existing objectStore in an already existing indexedDB?

I am tying myself up in knots trying to update a series of four entries in an objectStore in an indexedDB.
This is what I want to achieve (in pseudo-code):
let myDatabase = indexedDB('myDatabase', 1);
let myObjectStore = myDatabase.myObjectStore;
myObjectStore.entry1 = 'newValue1';
myObjectStore.entry2 = 'newValue2';
myObjectStore.entry3 = 'newValue3';
myObjectStore.entry4 = 'newValue4';
But of course, it isn't anything like that straightforward.
I understand I need to use put. But, despite numerous attempted approaches, I can't get further than that.
I have got as far as successfully setting up and populating the objectStore in the first place when the indexedDB is first created:
// SET UP VALUES OBJECT
let valuesObject = {
entry1 : 'a',
entry2 : 'b',
entry3 : 'c',
entry4 : 'd'
};
// SET UP INDEXED DATABASE
const setUpIndexedDatabase = (valuesObject) => {
let database
const databaseVersion = 1;
const databaseName = \'myDatabase\';
const databaseOpenRequest = indexedDB.open(databaseName, databaseVersion);
databaseOpenRequest.onupgradeneeded = () => {
database = databaseOpenRequest.result;
let myObjectStore = database.createObjectStore('myObjectStore');
myObjectStore.transaction.oncomplete = () => {
let objectStoreValues = database.transaction('Values', 'readwrite').objectStore('Values');
const valuesEntries = Object.entries(valuesObject);
for (let i = 0; i < valuesEntries.length; i++) {
objectStoreValues.add(valuesEntries[i][1], valuesEntries[i][0]);
}
}
}
databaseOpenRequest.onsuccess = () => {
database = databaseOpenRequest.result;
// >>> THIS IS THE BIT THAT I NEED TO WRITE <<<
database.close();
}
}
setUpIndexedDatabase(valuesObject);
So far, so good. The code above fires the onupgradeneeded event if no database exists yet, which creates myObjectStore and populates it with four key-value pairs.
But if the database does exist and already contains myObjectStore, then every variation of code I have written using put fails to update the values for the keys and returns various errors - and quite often no errors at all.
All I want to do is update values in the database.
I think the problem is that I don't know how to use put properly when the Database Version remains unchanged and onupgradeneeded doesn't fire.
If you want to update an already existing value in the database, you can do so with the following code (as example, I am updating the entry1 entry):
databaseOpenRequest.onsuccess = function(event) {
db = event.target.result;
const objectStore = db.transaction('myObjectStore', 'readwrite').objectStore('myObjectStore');
const request = objectStore.put('e', 'entry1');
request.onerror = function(event) {
// There was an error while updating.
};
request.onsuccess = function(event) {
// The update was successful.
};
}

Get the ChildrenCount of a child in Firebase using JavaScript

I have been doing this for an hour. I simply want to get the number of children in the child "Success" in the database below. The answers in similar stackoverflow questions are not working. I am new in Javascript Programming.
So far I have tried this
var children = firebase.database().ref('Success/').onWrite(event => {
return event.data.ref.parent.once("value", (snapshot) => {
const count = snapshot.numChildren();
console.log(count);
})
})
and also this
var children = firebase.database().ref('Success/').onWrite(event => {
return event.data.ref.parent.once("value", (snapshot) => {
const count = snapshot.numChildren();
console.log(count);
})
})
Where might I be going wrong.
As explained in the doc, you have to use the numChildren() method, as follows:
var ref = firebase.database().ref("Success");
ref.once("value")
.then(function(snapshot) {
console.log(snapshot.numChildren());
});
If you want to use this method in a Cloud Function, you can do as follows:
exports.children = functions.database
.ref('/Success')
.onWrite((change, context) => {
console.log(change.after.numChildren());
return null;
});
Note that:
The new syntax for Cloud Functions version > 1.0 is used, see https://firebase.google.com/docs/functions/beta-v1-diff?authuser=0
You should not forget to return a promise or a value to indicate to the platform that the Cloud Function execution is completed (for more details on this point, you may watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/).
const db = getDatabase(app)
const questionsRef = ref(db, 'questions')
const mathematicalLiteracy = child(questionsRef, 'mathematicalLiteracy')
onValue(mathematicalLiteracy, (snapshot) => {
const data = snapshot.val()
const lenML = data.length - 1
console.log(lenML)
})
This method worked for me. I wanted to get the children's count of the mathematicalLiteracy node in my database tree. If I get its value using .val() it returns an array that contains that node's children and an extra empty item. So, I subtracted that one empty item's count. Finally, I get my needed children's count.

Firebase Database: why do the key/ref in my queried datasnapshot refer to its parent?

I would like to delete an entry from the realtime database that i looked up through a query but i am getting unexpected results for both the ref and key properties.
ref('photos/users/USERID')
.orderByChild('photoname')
.equalTo('photoname i want to look up')
.limitToFirst(1)
.query('once')
.then(snapshot => {
// correct data at 'photos/users/USERID/PHOTOID'
const entry = snapshot.val();
// seems to be the ref to photos/users/USERID'
const ref = snapshot.ref;
// seems to be USERID
const key = snapshot.key
})
Why aren't these the ref/key to the entry i just found? And what is the best approach to remove this entry?
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to take this list into account, and iterate over snapshot.forEach() to get the actual matching item:
ref('photos/users/USERID')
.orderByChild('photoname')
.equalTo('photoname i want to look up')
.limitToFirst(1)
.query('once')
.then(snapshot => {
snapshot.forEach(child => {
const entry = child.val();
const ref = child.ref;
const key = child.key
});
})
Your ref and key are based on ref('photos/users/USERID'), not the filtered subset you have created. Is there any reason you wouldn't call ref('photos/users/USERID/PHOTOID')?

Categories

Resources