【问题标题】:Delete a document from subcollection in Firestore with node.js使用 node.js 从 Firestore 中的子集合中删除文档
【发布时间】:2018-07-20 09:21:12
【问题描述】:

我想从 Firebase 子集合中删除一个文档。我正在尝试通过以下方式执行此操作:

firestore.collection('categories').doc(categoryId).collection('books').doc(bookId).delete();

而且它不起作用。

但是,我可以从集合中删除一个文档:

firestore.collection('categories').doc(categoryId).delete();

我是不是看不到什么东西了?它应该如何工作?

更新:

const firebase = require('../firebase/firebaseAdmin');
const firestore = firebase.firestore();

module.exports = {
  removeBookFromCategory: (categoryId, bookId) => (
    firestore
      .collection('categories')
      .doc(categoryId)
      .collection('books')
      .doc(bookId)
      .delete()
  ),
};

我在这里有正确的 ID,但我收到 500 错误:

错误:参数“documentPath”不是有效的 ResourcePath。路径必须 是一个非空字符串。

【问题讨论】:

  • 您能否编辑问题以显示数据的确切内容、您正在使用的变量的值以及 delete() 返回的承诺的结果(是否通过错误?)。
  • 这样做应该没问题
  • 如果您的删除未被安全规则允许或未能通过身份验证,则可能会出现问题。请用我之前提出的问题更新您的问题,尤其是 delete() 返回的承诺的结果。
  • 啊,我的问题是错误的端点!我有: router.delete('/categories/:id/books/:id/remove', removeBook);而不是 router.delete('/categories/:categoryId/books/:bookId/remove', removeBook);

标签: node.js firebase google-cloud-firestore


【解决方案1】:

当您删除具有关联子集合的文档时,子集合不会被删除。它们仍然可以通过参考访问。 执行时,

firestore.collection('categories').doc(categoryId).collection('books').doc(bookId).delete();

它将删除文档。但它不会删除子集合。如果要删除子集合,则必须手动完成。 请参考here

【讨论】:

  • 我希望能够从子集合中删除唯一的文档。
  • 这也是一个重要的问题。感谢您关注此问题。
【解决方案2】:

我可能回答得太晚了,但我想通了。 如果您的数据库具有以下方案: rootCollection -> 文档 -> 子集合 -> documentInsideSubCollection

您可以使用下面的 sn-p 删除子集合中的文档:

  firestore.collection(rootCollection)
  .doc(documentName)
  .collection(subCollectionName).ref  
  .where(field, "==", something)
  .onSnapshot(snapshot => snapshot.forEach(result => result.ref.delete()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-17
    • 2018-11-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2018-05-05
    • 2018-10-19
    • 2018-08-08
    相关资源
    最近更新 更多