1 | initial version |
To establish a connection with Firebase in order to perform CRUD operations using Node.js, you need to follow these steps:
const admin = require('firebase-admin');
const serviceAccount = require('/path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
// 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.