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.initiali...

问题:

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


回答1:

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

  • 发表于 2018-12-30 11:49
  • 阅读 ( 275 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除