uzaysan
uzaysan

Reputation: 605

Firebase Function writes wrong key to firebase database

I have a cloud function and i call it directly in app.

my code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.sharePost = functions.https.onCall((data, context) => {
  var postkey = data.text;
  const uid = data.uid;

  var list= [];

  var db = admin.database();

var ref = db.ref("users").child(uid).child("followers");
  ref.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    list.push(childKey);
  });
  var refsave = db.ref("posts");

  for (var i = 0; i < list.length; i++) {
    refsave.child(list[i]).update({
      postkey:""
    });
  }

});

});

And i call this function with this code:

private Task<String> sharePost(String text) {
        Map<String, String> data = new HashMap<>();
        data.put("text", text);
        data.put("uid",auth.getUid());

        return mFunctions
                .getHttpsCallable("sharePost")
                .call(data)
                .continueWith(new Continuation<HttpsCallableResult, String>() {
                    @Override
                    public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                        String result = (String) task.getResult().getData();
                        return result;
                    }
                });
    }

I put post key(something like this : -LUpD2kWvUct5KiihU4M) in this task and what i wanna do is writing that key.but instead of that function write data under variable name.

This image tells better what i want

enter image description here

Upvotes: 1

Views: 361

Answers (1)

Umar Hussain
Umar Hussain

Reputation: 3527

Since you want to update multiple values you can create update object and write them all at once.

Also update is different then set(). Update object key is the path to update and value will be written at that path. Also the path is relative to the child on which you will call update().

Update your firebase functions like this:

var ref = db.ref("users").child(uid).child("followers");
ref.once('value', function (snapshot) {
    let update={};
    snapshot.forEach(function (childSnapshot) {
        var childKey = childSnapshot.key;
        update[`${childKey}/${postkey}`]="THE VALUE YOU WILL STORE"
    });
    var refsave = db.ref("posts");

    return refsave.update(update);

});

For more details on how update works in admin sdk please see the documents. https://firebase.google.com/docs/reference/admin/node/admin.database.Reference#update

Upvotes: 1

Related Questions