Brutal
Brutal

Reputation: 922

How to get Realtime Database in Firebase by using cloud function?

I've created Firebase project and added some data to Realtime Database? I also created cloud functions by using console. This is my following code

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

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

exports.addMessage = functions.https.onRequest(async (req, res) => {

 const snapshott = await admin.database().ref('/messages').push({"original":"ZXz"});

 res.send("assasin")
});
exports.getMessage = functions.https.onRequest(async (req, res) => {

    const snapshott = await admin.database().ref('/messages').get();

    res.send(snapshott)
});

The addMessage function works fine but getMessage function gives an error.

This is the following error

TypeError: admin.database(...).ref(...).get is not a function
    at exports.addMessage.functions.https.onRequest (/srv/index.js:15:60)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

So how can I get Realtime Database in Firebase by using cloud function?

Upvotes: 2

Views: 2457

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

As you will see in the doc, there is no get() method for a Realtime Database Reference. On the other hand, Firestore, the other NoSQL Database offered by Firebase has a get() method. You are probably mixing up the two database services :-)

To read a node in the Realtime Database, you need to use the once() method.

So, in your case you would do as follows:

exports.getMessage = functions.https.onRequest(async (req, res) => {

    const snapshott = await admin.database().ref('/messages').once('value');

    res.send(snapshott);

});

Two extra things to note:

  1. You can also use the on() method to read a node, but this method is not commonly used in Cloud Functions, since it sets a listener which continuously "listens for data changes at a particular location".
  2. You should manage errors in your Cloud Function, see this official video: https://firebase.google.com/docs/functions/video-series#learn-javascript-promises-pt1-with-http-triggers-in-cloud-functions

Upvotes: 3

Related Questions