How to connect firebase with node js & crud operation

 

How to Connect FireStore Database with Nodejs And Express.

 Step 1: Go to the firebase console and click on Add Project.
             


 Step 2: Enter a name for your project and click on continue.



 Step 3: On this screen, if you want Google Analytics enable just click on continue by                          default it is enabled else unstick it.



 Step 4: If you have a Google Analytics account select it otherwise selects Default Account                for Firebase.



 Step 5: Now it will take some time to get your project ready.



 Step 6: Finally your project is ready on firebase.



    This is your project dashboard screen.



    Create a web app by clicking on the </> symbol


    Enter your web App name



    Click on Register App


    Click on Next


     Follow the steps to integrate it with your backend .

   
   Click on Next




     Copy this config details


   In  the firestore you can start with new database.




    It will ask for permissions and mode of database while creating new database.


   Click on Start.



   Now you can start with new collection.


   Change rule read-write true




Let's start with node,

Step 1: Install node js using the following command.

           npm init -y


Step 2:  We need to install express js by following the command.

                 npm install express

Step 3: To connect with the firebase install the firebase node package.

npm install firebase



const express = require("express");

const firebase = require("firebase");

 

const app = express();





Step 4: To fetch data from the database 


app.get('/getData', (req, res) => {
(async () => {
try {
let response = []
console.log('hii')
await db.collection('store').get().then(querySnapshot => {
let docs = querySnapshot.docs
for (let doc of docs) {
response.push(doc.data())
}
return res.status(200).send(response)
})
} catch (err) {
console.log(err)
return res.status(500).send(err)
}
})()
})


Step 5 :  Open postman 
             - Add new GET request 
             - Copy local server path 
               Local server path: "http://localhost:4000"
             - Write your function name preceeding with '/getData' (function name) .


           
Step 6: To delete data from the database


app.delete('/delete/:bookId', (req, res) => {
(async () => {
try {
let bookId = req.params.bookId;
console.log(bookId)
await db.collection('store')
.doc(bookId)
.delete();
return res.status(200).send();

} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});


Step 7: To update data to the database


app.post('/updateData', (req, res) => {
(async () => {
try {
const bookDetail = req.body;
console.log(bookDetail.id)
await db.collection('store')
.doc(bookDetail.id).update({
bookName : bookDetail.bookName,
})
return res.status(200).send();

} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});


Step 8: To post(Add new) data into the database 



app.post('/addData', (req, res) => {
(async () => {
try {
const bookDetail = req.body;
console.log(bookDetail)
await db.collection('store')
.doc(bookDetail.id)
.set(JSON.parse(JSON.stringify(bookDetail), { merge: true }));
return res.status(200).send();

} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});






const
port = process.env.PORT || 4000;

 

app.listen(port, () => {

 console.log(`Server is running on port ${port}.`);

});

 








final code with complete functionality


const express = require("express");

const firebase = require("firebase");

const app = express();




app.get('/getData', (req, res) => {
(async () => {
try {
let response = []
console.log('hii')
await db.collection('store').get().then(querySnapshot => {
let docs = querySnapshot.docs
for (let doc of docs) {
response.push(doc.data())
}
return res.status(200).send(response)
})
} catch (err) {
console.log(err)
return res.status(500).send(err)
}
})()
})


app
.post('/updateData', (req, res) => {
(async () => {
try {
const bookDetail = req.body;
console.log(bookDetail.id)
await db.collection('store')
.doc(bookDetail.id).update({
bookName : bookDetail.bookName,
})
return res.status(200).send();

} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});


app.post('/addData', (req, res) => {
(async () => {
try {
const bookDetail = req.body;
console.log(bookDetail)
await db.collection('store')
.doc(bookDetail.id)
.set(JSON.parse(JSON.stringify(bookDetail), { merge: true }));
return res.status(200).send();

} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});


app.delete('/delete/:bookId', (req, res) => {
(async () => {
try {
let bookId = req.params.bookId;
console.log(bookId)
await db.collection('store')
.doc(bookId)
.delete();
return res.status(200).send();

} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});


const
port = process.env.PORT || 4000;

app.listen(port, () => {

 console.log(`Server is running on port ${port}.`);

});






In this way we successfully learnt about firebase and its installation.
Keep learning.

Thank you :)




Comments

Post a Comment