【问题标题】:Query delete in Firestore is deleting everything, how to fix it?Firestore中的查询删除正在删除所有内容,如何解决?
【发布时间】:2019-01-29 12:02:17
【问题描述】:

我需要从集合中删除所有文档,但我应该只删除 'pedido' 等于 'this.pProdutos' 的地方。问题是,即使在查询之后,它也会删除整个集合中的所有文档。 我现在正在使用下面的代码:

    this.db.collection('produtosPedidos', ref => ref.where('pedido', '==', this.pProdutos)).ref
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach((doc) => {
        doc.ref.delete().then(() => {
          console.log("Document successfully deleted!");
        }).catch(function(error) {
          console.error("Error removing document: ", error);
        });
      });
    })
    .catch(function(error) {
      console.log("Error getting documents: ", error);
    });

【问题讨论】:

  • 您是否尝试过从 querySnapshot 中列出文档?这是整个系列吗?如果是这样,查询可能有问题
  • 查询实际上是正确的,我总是将它显示在一个表格(购物车)中,它只检索与pProdutos相关的数据,但只有在删除它时才会删除所有内容......跨度>

标签: javascript google-cloud-firestore angularfire2


【解决方案1】:

问题是由您在此处查询末尾的尾随 .ref 引起的:

ref.where('pedido', '==', this.pProdutos)).ref

第一部分ref.where('pedido', '==', this.pProdutos)) 构造一个查询,但随后对该查询调用ref 会向整个集合返回一个CollectionReference。删除尾随的.ref,它应该可以工作。

this.db.collection('produtosPedidos', ref => ref.where('pedido', '==', this.pProdutos))
    .get()
    .then(querySnapshot => {
        ...

对于这种类型的操作,通过 AngularFire 运行它并没有额外的好处。我建议只在裸 JavaScript SDK 上运行它,以减少代码量。由于 AngularFire 构建在 JavaScript SDK 之上,因此当您执行此操作时,两者可以完美地互操作。

在代码中:

firebase.firestore().collection('produtosPedidos').where('pedido', '==', this.pProdutos)
    .get()
    .then(querySnapshot => {

【讨论】:

  • 它说“'AngularFirestoreCollection' 中不存在属性'where'”。我认为这是因为我使用了这个:“私人数据库:AngularFirestore”。如何解决?
  • 抱歉,我用直接调用 JavaScript API (firebase.firestore().collection(...)) 替换了对 AngularFire (this.db.collection()) 的调用。
  • 如何准确调用“firebase”的导入?我忘记了。
  • 我不愿意在这个项目中使用fireAuth,导入'admin'的东西会导致任何类型的问题吗?
【解决方案2】:

  deleteOffice(office) {
    this.firestore
      .collection('offices', (ref) => ref.where('name', '==', office.name))
      .get()
      .subscribe((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          doc.ref
            .delete()
            .then(() => {
              console.log('Document successfully deleted!');
            })
            .catch(function (error) {
              console.error('Error removing document: ', error);
            });
        });
      });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多