[英]How can I delete a document in Firebase after sorting by a specific field?
[英]Delete firebase document using field value
我正在嘗試刪除 firebase 文檔,但問題是我想刪除使用字段的特定文檔。
如上所示,我在許多文檔中都有 user_uid_1 和 user_uid_2。 我想匹配它們,就像單擊刪除時應刪除帶有(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);
});
};
};
您可以使用where
方法查詢並為找到的每個文檔循環delete()
方法。 請參閱下面的示例代碼:
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();
});
});
如果(401 and 337)
可以同時出現在user_id_1
和user_id_2
中,你可以做一個簡單的邏輯來檢查字段上是否出現。 請參閱下面的示例代碼:
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.