Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize Firebase V9 database in Node

I think I’m getting confused between firebase-admin and Web SDK I simply would like to connect a scheduled job that will push data into my Real-time database

Project structure

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

How can I correctly connect my scheduled cloud function to Firebase Database?

Here is my index.js where most scheduled functions will live

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
//const { push } = require("firebase/database")

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "myurl"
});

const database = admin.database();

exports.scheduledFunction = functions.pubsub
  .schedule("every 1 minutes")
  .onRun((context) => {
    push(database, "/hello", {
        message: "world"
    })
    return console.log("This will be run every 1 minutes!");
  });

>Solution :

The Admin SDK is not totally modular like the client SDK yet so you’ll have to use the namespaced syntax if using the Admin SDK:

const db = admin.database();

exports.scheduledFunction = functions.pubsub
  .schedule("every 1 minutes")
  .onRun((context) => {
    console.log("This will be run every 1 minutes!");
 
    return db.ref('hello').push({ name: "Hellow" });
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading