Reading data from Firestore database to a self made website

Viewed 88

So I am currently working on project where I have to send data that is continuously created in sigfox to firestore database, and read the data from sigfox in a self-created website. As well as host the website. So far I have managed to create a cloud function that allows me to send data from sigfox backend to firestore. However, I am having issues to try and read data from the Firestore database. Every time I use the command "firebase serve --only "hosting,functions" to check on my code, it would show me that the database does not exist. This is the code that I have written so far from based on videos from youtube.

const functions = require("firebase-functions");
const express = require('express');
const engines = require('consolidate');
var hbs = require('handlebars');
const admin = require('firebase-admin');
const app = express();

app.engine('hbs',engines.handlebars);

app.set('views', './views');

app.set('view engine', 'hbs');

const { service } = require("firebase-functions/v1/analytics");
const { response } = require("express");

var serviceAccount = require("./unabiz-firebase-firebase-adminsdk-ehtzo-0b37e0cf1f.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "firebase-adminsdk-ehtzo@unabiz-firebase.iam.gserviceaccount.com"
  });


async function getFirestore() {
    const firestore_con = await admin.firestore();

    const writeResult = firestore_con.collection('device').doc("device").get().then(doc=> 
        {
            if (doc.exists) {return doc.data();}
            else {console.log("No such document!");}})
    .catch(err => {console.log('Error getting document', err);})

}

app.get('/',async (request,response) => {
    var db_result = await getFirestore();

    response.render('index', {db_result});

})


exports.app = functions.https.onRequest(app)

Here is also a photo of my database the data that it contains:

enter image description here

Do note that the cloud function I am using was created in at a separate time, and different file. What can I do to solve the issue I am facing?

1 Answers

Two things:

  1. The reason you're getting the database does not exist error is that the value you're giving in url is not the Firebase URL but rather the Service Account associated with the app. Which, to my knowledge, is not how you initialize Firebase Admin

  2. I would like to note that the Firebase Admin SDK does perform all of these operations with administrative permissions, which means that it should only be used by Administrators and the like, so the use of this app should be restricted to those with high administrative privileges to avoid malicious intent or, more likely, mistakes causing irreparable damage to your Firestore database or the data within.

Related