简体   繁体   中英

Android - Firebase Firestore - Write the same document to different collections

I have to write the same document to different collections, so I think that batched writes are not good for this. I would like to know if there is a function in firestore database, I expect written in javascript, that can copy a document I write once and paste it to different locations. These locations should be read from an array in the database.

Anyone could help me?

Thanks a lot and sorry for my low English.

The Batched writes in Cloud Firestore are meant for this exact purpose.

You can execute multiple write operations as a single batch that contains any combination of set(), update(), or delete() operations. A batch of writes completes atomically and can write to multiple documents.

And as a response to your question, yes, you can write the same document to different collections using this the batched writes operation.

And this how it looks like in code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference productsRef = rootRef.collection("products");
CollectionReference newProductsRef = rootRef.collection("newProductsRef");

WriteBatch writeBatch = rootRef.batch();
batch.set(productsRef.document(), yourObject);
batch.set(newProductsRef.document(), yourObject);

// This how you commit the batch
writeBatch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        // ...
    }
});

Using this code, you'll be able to write the same yourObject object to two different location in your Cloud Firestore database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM