Home > database >  Can i record changes on firestore documents?
Can i record changes on firestore documents?

Time:03-04

I'm working on a project with Firebase and Firestore, I have a collection that has a status attribute and I wanna record the time that a document is updated and who updated it. There's no documentation for this Does anyone have a solution?

CodePudding user response:

There is nothing built-in that can help you achieve that. If you want to track the changes that are made to a document and know who made them, you have to create a mechanism for that yourself.

Assuming that you have a document with a particular ID, you can create a subcollection in which you can add as documents the changes that are made. A possible database schema would look like this:

Firestore-root
   |
   --- users (collection)
        |
        --- $uid (document)
             |
             --- changes (collection)
                  |
                  --- $changeId (document)
                        |
                        --- timestamp: Febrary 4, 2022 at 2:46:19 PM UTC 3
                        |
                        --- madeBy: "UidOfTheUser"

In this way you can keep a history of the changes that are made to a particular document.

CodePudding user response:

Something like this happened to me when i wanted to retrive live messages from Firebase so i used Stream Builder to catch all new messages in the stream.

Here is the code i used!

class MessagesStream extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore.collection('messages').orderBy('time').limitToLast(100).snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: Colors.lightBlueAccent,
            ),
          );
        }
        final messages = snapshot.data.docs.reversed;
        List<MessageBubble> messageBubbles = [];
        for (var message in messages) {
          final messageText = message.data()['text'];
          final messageSender = message.data()['sender'];
          final currentUser = loggedInUser.email;
          final messageBubble = MessageBubble(
            sender: messageSender,
            text: messageText,
            isMe: currentUser == messageSender,
          );
          messageBubbles.add(messageBubble);
        }
        return Expanded(
          child: ListView(
            reverse: true,
            padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
            children: messageBubbles,
          ),
        );
      },
    );
  }
}
  • Related