Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
db not defined firebase firestore

I am to make a blog website that can save and publish written articles within the website. I am using firebase firestore to save my data there but only problem is that when i run it, it say db is not defined at HTMLButtonElement

HTML

   <script
      type="module"
      src="https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js"
    ></script>
    <script
      type="module"
      src="https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js"
    ></script>

    <script type="module" src="js/editor.js">
      firebase.initializeApp({
        apiKey: "AIzaSyBbHBS9rdHrbP6g7BG4_kPP9XV1vCiVewU",
        authDomain: "blog-web-49668.firebaseapp.com",
        projectId: "blog-web-49668",
        storageBucket: "blog-web-49668.appspot.com",
        messagingSenderId: "561111016179",
        appId: "1:561111016179:web:eef336738659e3fbfb0d86",
      });

      var db = firebase.firestore();
      db.settings({ timestampsInSnapshots: true });
    </script>

Javascprit

publishBtn.addEventListener('click', () => {
    if (articleField.value.length && blogTitleField.value.length) {
        // generating id 
        let letters = 'abcdefghijklmnopqrstuvwxyz';
        let blogTitle = blogTitleField.value.split("-").join("-");
        let id = '';
        for (let i = 0; i < 4; i++) {
            id += letters[Math.floor(Math.random() * letters.length)];
        }

        // setting up docName
        let docName = `${blogTitle}-${id}`;
        let date = new Date(); // for published at info

        //access firestore with db variable;
        db.collection("blogs").doc(docName).set({
            title: blogTitleField.value,
            article: articleField.value,
            bannerImage: bannerPath,
            publishedAt: `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
        })
            .then(() => {
                console.log('date entered');
            })
            .catch((err) => {
                console.error(err);
            });
    }
})

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need to remove src="js/editor.js" from the script tag:

<script type="module" src="js/editor.js">
   firebase.initializeApp({...
   // ...
</script>

should be

<script type="module">
   firebase.initializeApp({...
   // ...
</script>
about 4 years ago · Juan Pablo Isaza Report

0

i have the same problem, i solve in this way

Hello, try to put this code in the "firebase.js":

let firebaseConfig = {
  //your information
  };

 // Initialize Firebase
 firebase.initializeApp(firebaseConfig);

 const db = firebase.firestore();

 export async function insert(item) {
    try {
     const response = await db.collection("blogs").add(item);
     return response;
    } catch (error) {
     throw new Error(error);
      }
 }

 export async function getItems(uid) {
    try {
       let items = [];
       const response = await db
      .collection("blogs")
       .where("userid", "==", uid)
       .get();

       response.forEach(function (item) {
       items.push(item.data());
        });

       return items;
     } catch (error) {
        throw new Error(error);
       }
  }
   
   export async function update(id, completed) {
       try {
          let docId;
          const doc = await db.collection("blogs").where("id", "==", id).get();
          doc.forEach((i) => {
          docId = i.id;
          });

        await db.collection("blogs").doc(docId).update({ completed: completed 
         });
       } catch (error) {
            throw new Error(error);
         }
    }
  export { db };

and in the js files import:

    import { insert, getItems, update, db } from "./firebase.js";
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!