简体   繁体   中英

How to update all collection in firebase firestore in flutter

I have two collections. One collection "User", who contains the user info (name...) And one collection "Post" who contains all posts of my flutter application. A post document contains many fields like a "Title", "Name" of the user. I add an option in my application to allow the user to change his name. But I must change the name in the "User" collection and in all posts it creates in the "Post" collection. How should I do it? Can anyone help me with an example?

There's nothing magical here. You'll need to get all post documents for that user with a query , and then update them one by one or in batches .

I'd also recommend checking out: What is the fastest way to write a lot of documents to Firestore?

Depends on which firestore are you using.

For Cloud Firestore:

You can update like this way, this is the case where you are updating just one field of your user.

final docRef = db.collection("users").doc("user_id");
final updates = <String, dynamic>{
  "timestamp": FieldValue.serverTimestamp(),
};

docRef.update(updates).then(
    (value) => print("DocumentSnapshot successfully updated!"),
    onError: (e) => print("Error updating document $e"));

For updating a nested field:

// Assume the document contains:
// {
//   Title: "Post Tittle",
//   Name: "Post Name"
//   user: { id: "1", name: "User Name" }
//   date: "2022-12-08"
// }
db
    .collection("posts")
    .doc("post_id")
    .update({"date": "2022-13-08", "user.name": "New name"});

You can see more details here:https://firebase.google.com/docs/firestore/manage-data/add-data

Assuming there is a user id attached to each post, you can query from the posts collection where the user (that is changing his/her name) id matches the id that is in the post (from the posts collection) and then modify the user property/attribute from the results.

A sample code would look like this,

To modify from the user collection

final docRef = FirebaseFirestore.instance
    .collection('users')
    .doc(id);

final response = await docRef
    .update(updatedDateInJson)
    .then((value) => value)
    .onError((error, stackTrace) => error);

To modify from the posts collection where the user is found in a post

final response = FirebaseFirestore.instance
          .collection('posts')
          .where('name', isEqualTo: 'John')
          .get()
          .then((value) async {
              // modify each doc
          });

Quick Note: use a onError block to check for errors in updating docs.

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