如何使用Ruby删除Firestore集合

时间:2018-06-13 05:28:47

标签: ruby-on-rails google-cloud-firestore

我正在尝试使用Ruby删除Firestore中集合中的所有文档。

当我根据我认为的文档引用调用delete方法时,我得到一个例外。我检查了由collection_ref.get()返回的对象类型,发现它是一个DocumentSnapshot,如何访问DocumentRef以便我可以删除每个文档。

异常

undefined method `delete' for #<Google::Cloud::Firestore::DocumentSnapshot:0x0000000732e748>

代码

class FirestoreUtil

  def self.delete_collection(collection_name, batch_size)
    firestore = Google::Cloud::Firestore.new(project_id: 'jg-jai-test', credentials: "./google-cloud-key.json")

    collection_ref = firestore.collection(collection_name)

    collection_ref.get() do |doc|
      # Throws an exception
      # undefined method `delete' for #<Google::Cloud::Firestore::DocumentSnapshot:0x0000000732e748>
      doc.delete()

      # undefined method `batch' for #<Google::Cloud::Firestore::Query:0x0000000842d170>
      doc.ref.delete() # also throws exception
    end

  end

end

我能够让它像这样工作,但似乎这是一种低效的做事方式

class FirestoreUtil

  def self.delete_collection(collection_name, batch_size)
    firestore = Google::Cloud::Firestore.new(project_id: 'jg-jai-test', credentials: "./google-cloud-key.json")

    collection_ref.get() do |doc|

      # From the snapshot, get the document ref and then delete it
      doc_ref = firestore.doc "#{collection_name}/#{doc.document_id}"
      doc_ref.delete()

    end

  end

end

0 个答案:

没有答案