Firebase更新特定字段? [英] Firebase Update specific fields?

查看:201
本文介绍了Firebase更新特定字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var admin = require(firebase-admin); 


//获取服务帐号密钥JSON文件内容
var serviceAccount = require(service.json);

//使用服务帐户初始化应用程序,授予管理员权限

admin.initializeApp({
凭证:admin.credential.cert(serviceAccount),
databaseURL:DATABASE_URL

});

var db = admin.database();
var ref = db.ref(games);

var fs = require('fs');
var filePath ='games / 2017-06-27.json';
var file = fs.readFileSync(filePath);
$ b fs.watchFile(filePath,function(){

var request = require('request');

var usersRef = ref.child ('2017-06-27');



请求('http://URL/games/2017-06-27.json',function(error, (!error&&& response.statusCode == 200){

var asJson = JSON.parse(body)


usersRef.update(asJson)

}
})

});因此,我得到一个与实时运动数据分数,游戏状态等(使用另一种服务)的JSON数据库, 。然后,我使用节点来检查存储数据的文件上的更改并写入Firebase数据库。它工作正常,但我不想取代数据库。我只是想更新更改的字段,因为我有其他服务将额外的数据添加到我想要保留的数据库中的这个孩子。如何更新只有更改的字段而不更换所有的数据库,并保持其他额外的数据不是来自这个请求?

解决方案当您在某个位置调用 update()时,Firebase会循环传入的数据(在您的情况下, asJson ),并为每个键执行 ref.child(key).set(value)

< (key)=> {
usersRef.child(key).set(asJson [key]);
(< code> Object.keys(asJson).forEach })

所以当它合并的顶层属性asJson usersRef 下的现有数据,它仍然替换每个键下的数据。



你也想在这个层次上进行合并,你必须把JSON从一棵树转换成一个路径列表。说你的JSON如下所示:

  {
user1:{
name:Speed_John
$,
user2:{
name:Frank van Puffelen
}
}

您必须将其转换为:

  {
user1 / name:Speed_John,
user2 / name:Frank van Puffelen
}

var JSON = {user1:{name:Speed_John},user2:{name:Frank van Puffelen ,id:209103}}; var updates = {}; function flatten(json,prefix){Object.keys(json).forEach((key)=> {var path =(prefix ||)+ /+ key; if(typeof json [key] ===object){flatten(json [key],path);} else {updates [path] = json [key];}});} flatten JSON);执行console.log(更新);



使用这段代码,你可以调用:

  usersRef .update(更新); 


Im updating my firebase database continuously with this code:

var admin = require("firebase-admin");


// Fetch the service account key JSON file contents
var serviceAccount = require("service.json");

// Initialize the app with a service account, granting admin privileges

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "DATABASE_URL"

});

var db = admin.database();
var ref = db.ref("games");

var fs = require('fs');
var filePath = 'games/2017-06-27.json';
var file = fs.readFileSync(filePath);

fs.watchFile(filePath, function() {

var request = require('request');

var usersRef = ref.child('2017-06-27');



request('http://URL/games/2017-06-27.json', function (error, response, body) {
  if (!error && response.statusCode == 200) {

    var asJson = JSON.parse(body)


    usersRef.update(asJson)

   }
})

});

So I get a json with real-time sports data scores, game status etc (using another service). I then use node to check changes on the file where the data is stored and write to the firebase database. It works fine, but I don't want to replace the DB. I just want to update the fields that change, because I have other service adding extra data to this child in the database that i want to keep. How can I update only the fields with changes without replacing the all Database and that way keep other extra data that don't come from this request?

解决方案

When you call update() on a location, Firebase loops over the data that you pass in (in your case asJson) and for each key performs a ref.child(key).set(value).

Object.keys(asJson).forEach((key) => {
  usersRef.child(key).set(asJson[key]);
})

So while it merges the top-level properties of asJson with the existing data under usersRef, it still replaces the data under each key.

If you want to merge on that level too, you'll have to convert the JSON from a tree into a list of paths. Say your JSON looks like this:

{
  user1: {
    name: "Speed_John"
  },
  user2: {
    name: "Frank van Puffelen"
  }
}

You will have to convert this to:

{
  "user1/name": "Speed_John",
  "user2/name": "Frank van Puffelen"
}

var JSON = {
  user1: {
    name: "Speed_John"
  },
  user2: {
    name: "Frank van Puffelen",
    id: 209103
  }
};

var updates = {};
function flatten(json, prefix) {
  Object.keys(json).forEach((key) => {
    var path = (prefix||"")+"/"+key;
    if (typeof json[key] === "object") {
      flatten(json[key], path);
    }
    else {
      updates[path] = json[key];
    }
  });
}

flatten(JSON);
console.log(updates);

With this code you can then call:

usersRef.update(updates);

这篇关于Firebase更新特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆