Firebase storage | how to update customMetaData with merge true - firebase

When uploading a file.. I have set the following custom meta data
const metadata = {
customMetadata: {
user: userId,
disabled: 'false'
},
};
and upload it like
uploadBytes(ref(this.str, invoicePath), invoiceFile, metadata),
Now some time later I would like to set disabled to true. Doing smth like this
const metadata = {
customMetadata: {
disabled: 'true',
},
};
updateMetadata(ref(this.str, invoicePath), metadata)
will remove the user key in the customMetaData
Is it possible to update it without setting the user key again??

As far as I know the metadata you pass always completely replaces the existing metadata for that object. If you want to retain values from the previous metadata, you will have to perform a read-modify-write sequence.
Update: Interestingly enough the documentation on updating metadata says:
You can update file metadata at any time after the file upload completes by using the updateMetadata() method. Refer to the full list for more information on what properties can be updated. Only the properties specified in the metadata are updated, all others are left unmodified. updateMetadata() returns a Promise containing the complete metadata, or an error if the Promise rejects.

Related

Determine RTDB url in a trigger function

i m bulding a scalable chat app with RTDB and firestore
here is my raw structure of shards
SHARD1
Chats {
chat01: {
Info: {
// some info about this chatroom
},
Messages ...
}, ....
}
SHARD2...
now i have write triggers on all the info nodes of all the shards.
i want get the ID of the shard
How do i know what shard it actually ran on ?
[EDIT]
console.log(admin.app().name); // it prints "[DEFAULT]" in console
Puf and team please help
When a Realtime Database trigger is invoked, the second argument is an EventContext object that contains information about the database and node that was updated. That object contains a resource string, which has what you're looking for. According to the documentation for that string, it's name property will be formatted as:
projects/_/instances/<databaseInstance>/refs/<databasePath>
The databaseInstance string is what you're looking for. So, you can just split the string on "/" and take the 4th element of that array:
export const yourFunction = functions.database
.instance('yourShard')
.ref('yourNode')
.onCreate((snap, context) => {
const parts = context.resource.name.split('/')
const shard = parts[3]
console.log(shard)
})
If all you need is a reference to the location of the change, in order to perform some changes there, you can just use the ref property on the DataSnapshot that was delivered in the first argument, and build a path relative to there.

Firebase Cloud Firestore create entry or update if it already exists

I have an issue of knowing when to add or update an entry to a Firebase Firestore database.
Using doc_ref.set will add a document if it does not exist. It will also override all of a documents fields if it already exists and set is called.
Using doc_ref.update will update fields of a document if the document exists. If the document does not exist, nothing happens.
How do I add a new field to a document if the field does not currently exist, or update the field if it does exist? I could read the database and check if the field exists, and then use either set or update, but surely there is an easier way?
What you're looking for is the merge option in the set operation. From the documentation on setting a document:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.
I had similar problem, but I wanted to update array field using FieldValue.arrayUnion, FieldValue.arrayRemove. Therefore could not use set/merge.
To avoid checking if document exists before update (costs 1 read), I wrapped update statement with try/catch and check for error code 5 (NOT FOUND). In this case, set value instead of update.
Code example:
try {
await docRef.update({
arrayField: admin.firestore.FieldValue.arrayUnion(...dates),
});
} catch (error) {
if (error.code === 5) {
// Error: 5 NOT_FOUND: no entity to update:
await docRef.set({
arrayField: dates,
});
}
}

Firestore document Set with mergeFields when creating a document does not work as expected

Hi I am saving a documemnt with a batch write like so:
batch.set(admin.firestore().collection('suuntoAppWorkoutQueue').doc(generateIDFromParts([serviceToken.userName, payload.workoutKey])), <QueueItemInterface>{
userName: serviceToken.userName,
workoutID: payload.workoutKey,
retryCount: 0,
processed: false,
}, {mergeFields: ['retryCount']});
According to the docs:
Changes the behavior of set() calls to only replace the specified field paths. Any field path that is not specified is ignored and remains untouched.
Above it is said that it will only replace.
However, when I write a new document, eg the doc ID is does not exist the mergeFields only writes the retryCount field.
Is that by design?
Shouldn't then be saying:
Changes the behavior of set() calls to only write
Instead of:
Changes the behavior of set() calls to only replace
I can follow your argumentation about write/replace. I did not check the behavior myself, but if the field is written if the document does not exist 'write' or 'update' would be a better suited description of the behavior than replace as there is nothing to be replaced in the first place.
If you only want to update the field if the document already exists, you can use a transaction to do so. You can use the transaction to get the latest version of the document, check if it exists and if so update it.
let data = {
userName: serviceToken.userName,
workoutID: payload.workoutKey,
retryCount: 0,
processed: false,
}
let db = admin.firestore()
let documentReference = db.collection('suuntoAppWorkoutQueue').doc(...)
db.runTransaction((transaction) =>
transaction.get(documentRef).then((doc) => {
if (doc.exists) {
return t.update(documentRef, {retryCount: data.retryCount});
} else {
return t.set(documentRef, data);
}
}
).then(...).catch(...)
Transactions also have the benefit to be atomic. If the value on the server has changed since you fetched it, the transaction will fail. Firestore actually will re-run your code in this case to re-attempt the update. This eliminates race conditions.

Firebase query download the whole database. Why?

I try to download and show only specific data from the Realtime Database. I have the following code:
getUserPlatformIos() {
this.dataRef = this.afDatabase.list('data/users', ref => ref.orderByChild('meta/platform').equalTo('ios'));
this.data = this.dataRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
return this.data;
}
My firebase database structure
Firebase rules
Why firebase does download the whole database if I query before? This causes very long loading times and a lot of downloaded data....
Indexes need to be defined at the place where you the query. Since you run the query on data/users, that's where you need to define your index:
"users": {
".indexOn": "meta/platform"
}
This defines an index on users, which has the value of the meta/platform property of each user.
Note that the log output of your app should be showing an error message with precisely this information. I highly recommend checking log output whenever something doesn't work the way you expect it to work.

Vue-Firebase: Updating children & writing to child

I started working with Firebase and Vue also with VueFire and i dont understand how to update child nodes at Firebase.
I opened a firebase project and connected to it and i can push data to it.
Firebase
I made a vue component
import db from '../FireBase'
let team = db.ref('Teams');//Reference to Teams at firebase
let miss = db.ref().child('Teams'); //Attempt to get to the children of Teams
export default {
name: "App",
firebase: {
Teams_loc: db.ref('Teams'),
Mission: this.Teams_loc.child('Teams'),
missionKey: db.ref().child('Teams').push("").key,
},
...
I manage to get the Teams from firebase and send data to it:
this.$firebaseRefs.Teams_loc.push({
"test": "tester"
});
Which works but when i try to update the children inside
this.miss.push({
"where": "am i"
})
I get the following error
Cannot read property 'child' of undefined
And when i try to update a child
this.$firebaseRefs.missionKey.update(arr[0]);//arr[0] is an object
I tried looking at quite a few places but nothing seems to do the trick.
Thanks,
When you do the following you are doing an error at the second line.
Teams_loc: db.ref('Teams'),
Mission: this.Teams_loc.child('Teams'),
There is no child of the Teams node that has a key with the value `Teams.
So if you want to update an item, you first have to get its key (e.g. -LEzOBT-mp.....) and do as follows, as explained in the doc:
updateItem: function (item) {
// create a copy of the item
const copy = {...item}
// remove the .key attribute
delete copy['.key']
//possibly update (or add) some values of (to) the item
this.$firebaseRefs.Teams_loc.child(item['.key']).set(copy)
}
Also (if I am not mistaking) doing db.ref() will generate an error because you have to pass a value to ref().
I suggest that you study a bit more the doc and the example: https://github.com/vuejs/vuefire and https://github.com/vuejs/vuefire/blob/master/examples/todo-app/index.html
Update following your comment. Details on how to "know the random generated key"
According to the documentation:
Each record in the bound array will contain a .key property which
specifies the key where the record is stored. So if you have data at
/Teams/-LEzOBT-mp...../, the record for that data will have a .key of
"-LEzOBT-mp.....".
Look at this part of the doc: https://github.com/vuejs/vuefire#array-bindings.
So with this you will get all the keys of the Teams object. You have now to choose the item you want to update.
You could also declare a query in your firebase object, like:
firebase: {
team21483: this.database
.ref('Teams')
.orderByChild('teamCode')
.equalTo('21483')
}
and you would get an array with only one team, the one with TeamCode = 21483.
The best approach, in this latest case, is to manually bind to this Firebase query with the $bindAsArray (or possibly the $bindAsObject) instance methods, using a variable that you pass to equalTo().

Resources