Reputation: 922
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
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:
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".Upvotes: 3