I have created a new app in Firebase (not Firestore) via the creation Wizard. I have even entered some dummy data into my database via the web UI. How can I retrieve this data from the fireabase-admin SDK?
I have initialised my app like so:
import admin from "firebase-admin";
var serviceAccount = require("../private-key.json");
const app = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<my-db-url>.firebaseio.com/'
});
const db = app.database()
db
doesn't seem to have any get or set methods. What am I missing?
Following https://firebase.google.com/docs/database/admin/retrieve-data, it is not clear what db.ref
is. Do I need this?
How can I retrieve the data from my database?
The db.ref
represents a specific location in your Database and can be used for reading or writing data to that Database location.
You should check firebase.database.Reference for Properties and Methods that you can use.
Here's a sample snippet to read data from the Firebase Realtime Database:
var admin = require("firebase-admin");
// Initialize the app with a service account, granting admin privileges
admin.initializeApp({
databaseURL: "your-database-url"
});
// admin.database.enableLogging(true);
// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var ref = db.ref("Users");
var getPromise = ref.once("value", function(snapshot) {
console.log(snapshot.val());
});
return Promise.all([getPromise])
.then(function() {
console.log("Transaction promises completed! Exiting...");
process.exit(0);
})
.catch(function(error) {
console.log("Transactions failed:", error);
process.exit(1);
});
On the snippet above, we used snapshot.val()
to extract a value from a DataSnapshot
. The val() method may return a scalar type (string, number, or boolean), an array, or an object. It may also return null, indicating that the DataSnapshot is empty (contains no data).
You should also check DataSnapshot for available Properties and Methods that you can use.
We also used Promise.all()
method that takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises then catch if any error occurred.