Create, Read, Update and Delete are what is referred to as CRUD.
CRUD operations are present in almost every web app. In this tutorial I will explain how to perform CRUD operations in Node JS and Firebase.
I will assume that you have a project set up and ready.
CREATE OPERATION:
Let’s create a hypothetical user to demonstrate how to create and save data to the database
app.post('/create-user', (req, res) => {
const {name, email, password, phoneno, location } = req.body;
const auth = firebase.auth();
auth.createUserWithEmailAndPassword(email, password)
.then((user) => {
firebase.firestore().collection("users").doc().set({
"name": name,
"email": email,
"phoneno": phoneno,
"location": location,
})
.then(() => {
res.send('User created successfully');
});
})
.catch(err => {
res.send(err);
});
});
In the above code we are getting the user information ie name, email, password and location, from the request body, we then call the firebase auth method and use this auth method to authenticate the user profile using the user’s email and password
.then((user) => {
firebase.firestore().collection("users").doc().set({
"name": name,
"email": email,
"phoneno": phoneno,
"location": location,
})
.then(() => {
res.send('User created successfully');
});
})
Then we call an instance of Cloud firestore and save the user data in a document. The “.set()” method overwrites an existing document, if the document does not exist, it will create it with the data provided.
READ:
We will create a route that logs the user in;
app.post('/login', async(req, res) => {
try {
const {email, password} = req.body;
await firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
firebase.firestore()
.collection('customers')
.where('email', '==', email)
.get()
.then((users) => {
let value = users.docs[0].data();
res.json(value);
});
});
} catch (err) {
return res.status(400).send({ message: err.message });
}
});
Here we call the firebase auth method to authenticate the data provided in the request body, if the data is authenticated successfully, we then go on to find the user document in our cloud firestore using the user email.
.then((users) => {
let value = users.docs[0].data();
res.json(value);
});
We then call the docs method on the result returned from the firebase query to get the result as a list and the pick the first document (should only contain one document) and return it.
FIND ONE DOCUMENT
Here we are going to query the cloud firestore collection “users” for one document using the email provided and return the first document
app.get('/find-user', async(req, res) => {
const {email} = req.body;
await firebase.firestore()
.collection('users')
.where('email', '==', email)
.get()
.then((users) => {
let value = users.docs[0].data();
res.send(value);
});
});
FIRLTER DOCUMENTS BY MORE THAN ONE FIELD
We are going to query our cloud firestore and filter the data by more than one field in the document. Assume we want to find users in a particular location, that are also verified and also currently online.
app.post('/find-user', async (req, res) => {
let location = req.body.location;
let query = await firebase.firestore()
.collection('users')
.where('location', '==', location);
if(query != "") {
query = await query.where('verified', '==', "true");
}
if(query != "") {
query.where('status', '==', 'online')
.get()
.then(snapshots => {
if(snapshots.empty) {
return null;
}
let results = snapshots.docs.map(doc => doc.data());
return res.json(results[0]);
});
}
});
The “.where” method returns a collection query which we first check to see if it is not empty, if it’s not, we then filter by other fields, then we loop through the results and return the data of the first document.
UPDATE:
We will use the “.update” method to update an existing document in the cloud firestore. It only works if the document already exists before calling the update method
app.post('/update-user', async(req, res) => {
const {name, email, phoneno, location } = req.body;
try{
if(!req.body){
return res
.status(400)
.send({ message : "Data to update can not be empty"});
}
await firebase.firestore().collection('users')
.where('email', "==", email)
.update({
name : name,
description : req.body.description,
phoneno : phoneno,
location : location,
}).then((ref) => {
res.json(ref.data());
});
}
catch(err){res.status(500).send({ message : err.message || "Error Occurred while updating" });
}
});
DELETE:
Delete operation is pretty straightforward, call the “.delete” method on the document you want to remove
app.post('/delete-user', async(req, res) => {
const {email} = req.body;
await firebase.firestore()
.collection('users')
.where('email', "==", email)
.delete()
.then((ref) => {
res.json(ref.data());
});
});
DELETE VALUE FROM ARRAY:
app.post('/delete-value', async(req, res) => {
const {email, value} = req.body;
try{
await firebase.firestore().collection('users').doc(email).update({
[value] : firebase.firestore.FieldValue.delete()
});
res.json('successful operation');
}
catch(err){res.status(500).send({ message : err.message || "Error Occurred while deleting value" });
}
});
Top comments (0)