Firebase API for moving a tree branch from a collection to another one

隐身守侯 提交于 2019-12-13 19:40:44

问题


In my application, I need to move a quite big collection branch to another collection. Currently, I'm using something like that:

srcRef
 .startAt(start)
 .endAt(end)
 .once('value', function(snap) {
   destRef.set(snap.exportVal());
 });

Obviously, it is quite expensive, so my question is: Why Firebase does not provide a simple API for that? like:

srcRef.moveTo(destRef);

回答1:


You can use the Firebase CLI.

The Firebase CLI is installed with npm

sudo npm install -g firebase-tools

Then you can execute commands to get and set data:

firebase data:get / -f "<my-firebase-app>"

I have a personal project called firebase-dot-files that creates bash function to do common operations. One of them is transferring data. After you setup the bash functions you can do the following command:

transfer_to dev-firebase staging-firebase

You can also read this blog post for more information.

Firebase CLI as an npm module

The Firebase CLI can also be used a node module. This means you can call your usual CLI methods, but as functions.

Here is a simple data:get command:

var client = require('firebase-tools');
client.data.get('/', { firebase: '<my-firebase-db>', output: 'output.json'})
  .then(function(data) {
    console.log(data);
    process.exit(1);
  })
  .catch(function(error) {
    console.log(error);
    process.exit(2);
  });

To transfer data, you can combine a data:get, with a data:set.

function transfer(path, options) {
  var fromDb = options.fromDb;
  var toDb = options.toDb;
  var output = options.output;
  client.data.get(path, { firebase: fromDb, output: output })
    .then(function(data) {
      return client.data.set(path, output, { firebase: toDb, confirm: true });
    })
    .then(function(data) {
      console.log('transferred!');
      process.exit(1);
    })
    .catch(function(error) {
      console.log(error);
      process.exit(2);
    });
}

transfer('/', { fromDb: '<from>', toDb: 'to',  output: 'data.json' });


来源:https://stackoverflow.com/questions/34249965/firebase-api-for-moving-a-tree-branch-from-a-collection-to-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!