Home > Software design >  Delete firebase document using field value
Delete firebase document using field value

Time:03-30

I am trying to delete a firebase document but the problem is I want to delete specific documents using fields.

as seen above I have user_uid_1 and user_uid_2 in many documents. and I want to match them like every document with (401 and 337) should be deleted when I click delete.

    export const deleteChat = (chatId) => {
  return async (dispatch) => {
    const db = firestore();
    db.collection("conversations")
      .doc(chatId)
      .delete()
      .then(() => {
        dispatch({
          type: userConstants.GET_REALTIME_MESSAGES,
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };
};

CodePudding user response:

You could query using the where method and loop the delete() method for each document found. See sample code below:

const coversations = db.collection('conversations')
.where('user_id_1', '==', '401')
.where('user_id_2', '==', '337');

coversations.get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
    doc.ref.delete();
  });
});

If (401 and 337) can be in both user_id_1 and user_id_2, you can do a simple logic to check if there's an occurrence on the field. See sample code below:

const coversations = db.collection('conversations');

coversations.get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
    const n = ['401', '307'];
    if (n.includes(doc.data().user_uid_1) && n.includes(doc.data().user_uid_2)) {
      doc.ref.delete();
    }
  });
});
  • Related