Copy object from one node to another in Cloud Functions for Firebase

1.1k Views Asked by At

I'm using Cloud Functions for Firebase, and I'm stuck with what seems to be a very basic operation.

If someone adds a post, he writes to /posts/. I want a portion of that post to be saved under a different node, called public-posts or private-posts, using the same key as was used in the initial post.

My code looks like this

const functions = require('firebase-functions');

exports.copyPost = functions.database
  .ref('/posts/{pushId}')
  .onWrite(event => {
    const post = event.data.val();
    const smallPost = (({ name, descr }) => ({ name, descr }))(post);
    if (post.isPublic) {
      return functions.database.ref('/public-posts/' + event.params.pushId)
        .set(smallPost);
    } else {
      return functions.database.ref('/private-posts/' + event.params.pushId)
        .set(smallPost);
    }
  })

The error message I get is: functions.database.ref(...).set is not a function.

What am I doing wrong?

1

There are 1 best solutions below

1
On BEST ANSWER

If you want to make changes to the database in a database trigger, you either have to use the Admin SDK, or find a reference to the relevant node using the reference you've been given in the event. (You can't use functions.database to find a reference - that's used for registering triggers).

The easiest thing is probably to use event.data.ref (doc) to find a reference to the location you want to write:

const root = event.data.ref.root
const pubPost = root.child('public-posts')