Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To establish a connection with Firebase in order to perform CRUD operations using Node.js, you need to follow these steps:

  1. Create a Firebase account and create a new project.
  2. Add Node.js to your project by running the following command in your terminal: npm install firebase-admin --save
  3. Go to your Firebase project settings, click on Service accounts, and then click on Generate new private key. Save this file to your local machine.
  4. In your Node.js script, require the firebase-admin package and initialize it using the private key file you downloaded in step 3.
const admin = require('firebase-admin');
const serviceAccount = require('/path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});
  1. Once you have initialized Firebase in your Node.js script, you can perform CRUD operations on your Firebase database using the Firebase SDK.
// Create a new document in a collection
admin.firestore().collection('users').add({
  name: 'John Doe',
  age: 30,
  email: 'johndoe@gmail.com'
})
.then((docRef) => {
  console.log('Document written with ID: ', docRef.id);
})
.catch((error) => {
  console.error('Error adding document: ', error);
});

// Read a document from a collection
admin.firestore().collection('users').doc('docId').get()
.then((doc) => {
  if (doc.exists) {
    console.log('Document data:', doc.data());
  } else {
    console.log('No such document!');
  }
})
.catch((error) => {
  console.log('Error getting document:', error);
});

// Update a document in a collection
admin.firestore().collection('users').doc('docId').update({
  age: 35
})
.then(() => {
  console.log('Document updated!');
})
.catch((error) => {
  console.error('Error updating document: ', error);
});

// Delete a document from a collection
admin.firestore().collection('users').doc('docId').delete()
.then(() => {
  console.log('Document deleted!');
})
.catch((error) => {
  console.error('Error deleting document: ', error);
});

Note: This is just an example of how to perform CRUD operations using the Firebase SDK in Node.js. The specific operations you perform will depend on your use case and the structure of your Firebase database.