简体   繁体   中英

FIrebase or object/Array- how to add a number/value to a variable without using the variable value?

On my database i have a variable called user points, and i want to increase that variable by a value, lets say by 10, everytime i want.

I am doing this:

on firebase:

update({userPoints: +pointsToGet})

i am using the + to increase the value, but its not working. Is there any way that i can increase the userPoints without using the variable user points like this: userPoints = userPoints + pointsToGet

i tried using ++pointsToGet but it didnt work either

For Firestore

Yes you can by using firebase.firestore.FieldValue.increment(...) .

update({ userPoints: firebase.firestore.FieldValue.increment(pointsToGet) })

For more information check out this tutorial: https://fireship.io/snippets/firestore-increment-tips/

Or for the official docs, here: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#static-increment

For Realtime Database

No there is no solution for that, I would recommend you to stick to the following:

update({ userPoints: oldUserPoints + pointsToGet })

Or check out this answer, where someone explains how to do this with a transaction (which is better for race conditions): https://stackoverflow.com/a/40405392/9150652

Offtopic

Also just for your information, +pointsToGet returns the numeric value of your variable (which probably already is a number, so it will just return that number).

It is not used to add 1 to a variable. You can transform a string to a number with it. I hope the following snippet explains it a little:

 const createLog = (result) => { // Just a helper, so that we can see the "" for strings in the console return JSON.stringify({result}); } console.log(createLog( '123' )); console.log(createLog( +'123' )); console.log(createLog( '123' + '123' )); console.log(createLog( +'123' + +'123' ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM