简体   繁体   English

使用字段值删除 firebase 文档

[英]Delete firebase document using field value

I am trying to delete a firebase document but the problem is I want to delete specific documents using fields.我正在尝试删除 firebase 文档,但问题是我想删除使用字段的特定文档。

as seen above I have user_uid_1 and user_uid_2 in many documents.如上所示,我在许多文档中都有 user_uid_1 和 user_uid_2。 and I want to match them like every document with (401 and 337) should be deleted when I click delete.我想匹配它们,就像单击删除时应删除带有(401 和 337)的每个文档一样。

    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);
      });
  };
};

You could query using the where method and loop the delete() method for each document found.您可以使用where方法查询并为找到的每个文档循环delete()方法。 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.如果(401 and 337)可以同时出现在user_id_1user_id_2中,你可以做一个简单的逻辑来检查字段上是否出现。 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();
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM