【问题标题】:How to delete firebase firestore collection document if you don't know the document name?如果您不知道文档名称,如何删除 Firebase Firestore 集合文档?
【发布时间】:2021-03-26 01:01:31
【问题描述】:

我正在创建“将项目保存到收藏夹”功能,以便当用户单击心形图标时,该项目会添加到他的收藏中。但是我正在努力添加“不喜欢”功能,所以当用户再次单击心形按钮时,我想从他的收藏中删除该项目。

很遗憾,我无权访问该选定项目的文档 ID,但我知道使该项目在该文档中唯一的字段。

这是我正在尝试做的一些伪代码:

  const favoriteButtonUnlikeHandler = () => {
    db.collection("users")
    .doc(`${auth.currentUser?.uid}`)
    .collection("meals")
    // where document.ingredient_uid === recipePreview.ingredient_uid
    .delete()
  }

recipePreview 是我要删除的选定项目,recipePreview.ingredient_uid 是该项目的标识符。

如何筛选集合并找到与所选项目匹配的文档 ID?

编辑: 这就是我目前访问数据的方式:

  const [favoriteMeals, setFavoriteMeals] = useContext(favoriteMealsContext);

  useEffect(() => {
    db.collection("users")
      .doc(`${auth.currentUser?.uid}`)
      .collection("meals")
      .onSnapshot((snapshot) => {
        setFavoriteMeals(snapshot.docs.map((doc) => doc.data()));
      });
  }, []);

return (
<>
{favoriteMeals.map((meal) => (
              <MealResult/>
))}
</>
)

【问题讨论】:

  • 您的具体要求是什么?请至少粘贴示例数据库的屏幕截图
  • @pepe sry 刚刚添加,基本上我想遍历餐食收集并删除具有突出显示的成分_uid 值的文档的文档。
  • 如果你想删除一个文档,你应该有那个文档的文档ID。你在阅读文档时肯定会得到文档ID。顺便问一下你是如何访问数据的。?跨度>
  • 是什么阻止了你.where("ingredient_iod", "==", recipePreview.ingredient_uid)?见firebase.google.com/docs/firestore/query-data/queries#web_1

标签: javascript reactjs database firebase google-cloud-firestore


【解决方案1】:

如果您有关于文档的任何信息,例如成分 uid,您可以创建一个 query,其中包含您必须找到的信息。正如 cmets 中所建议的那样:

    var delete_query = db.collection("users").doc(`${auth.currentUser?.uid}`).collection("meals").where("incredient_uid", ==, recipePreview.ingredient_uid);
    delete_query.get().then(function(querySnapshot) {
        querySnapshot.forEach(function(doc){
            doc.ref.delete();
        });
    });

考虑到你需要使用 doc.ref 而不是直接使用 de .delete()

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 2018-12-10
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2021-11-14
    • 2018-08-08
    相关资源
    最近更新 更多