Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue creating a document with a known ID #40

Open
costag1982 opened this issue Jan 21, 2025 · 1 comment
Open

Issue creating a document with a known ID #40

costag1982 opened this issue Jan 21, 2025 · 1 comment

Comments

@costag1982
Copy link

Hi

I am trying to create a user with a known firebaseId using the uid from firebase authentication.

Here is my model

@Collection<UserDb>('users')
@firestoreSerializable
@JsonSerializable(createToJson: true)
class UserDb {
  UserDb({
    required this.id,
    required this.email,
    required this.firstName,
    required this.lastName,
    required this.createdDate,
    required this.groups,
    this.picture,
  });

  @Id()
  final String id;
  final String email;
  final String firstName;
  final String lastName;
  final DateTime createdDate;
  final Map<String, String> groups;
  final String? picture;

  factory UserDb.fromJson(Map<String, dynamic> json) => _$UserDbFromJson(json);
  Map<String, dynamic> toJson() => _$UserDbToJson(this);
}

final usersRef = UserDbCollectionReference();

As you can see in the model I have using the @ID annotation.

This works ok when I allow firebase to create an ID for me.

This is my code that creates the user

Future<UserDb> insertOneUser({
    required String firebaseId,
    required UserDbInsert user,
  }) async {
    try {
      final userData = UserDb(
        id: firebaseId,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        createdDate: Timestamp.now().toDate(),
        groups: user.groups,
      );

      final documentRef = _usersRef.doc(firebaseId);
      await documentRef.set(userData);

      final newUser = await documentRef.get();
      final userDoc = newUser.data;

      if (userDoc == null) {
        throw FirebaseException(
          plugin: 'cloud_firestore',
          message: 'Failed to retrieve the newly added user.',
        );
      }

      return userData;
    } on FirebaseException catch (e) {
      throw Exception('Firestore error (${e.code}): ${e.message}');
    } catch (e) {
      throw Exception('Error adding user: $e');
    }
  }

As you can see ID is required so I have to pass in firebaseID but what this does is created a docId as the firebaseId but also creates a duplicate ID in the user object.

Can this library not be smart enough to know to use this ID as the docID only.

Also in other collections where I dont care about the docID I have to pass in an empty string in the ID as its required like this

Future<PlayerDb> insertOnePlayer(PlayerDbInsert player) async {
    try {
      final playerData = PlayerDb(
          id: "",
          name: player.name,
          groupId: player.groupId,
          createdDate: Timestamp.now().toDate(),
          role: player.role,
          userId: player.userId,
          picture: player.picture,
          status: "active");

      final snapshot = await _playersRef.add(playerData);

      final newPlayer = await snapshot.get();
      final playerDoc = newPlayer.data;

      if (playerDoc == null) {
        throw FirebaseException(
          plugin: 'cloud_firestore',
          message: 'Failed to retrieve the newly added player.',
        );
      }

      return playerDoc;
    } on FirebaseException catch (e) {
      throw FirebaseException(
        plugin: 'cloud_firestore',
        message: 'Error adding player: ${e.message}',
      );
    }
  }

Im not sure im not using the library correctly as I don't such much documentation around writing data.

Please can you help?

Thanks
Costa

@costag1982
Copy link
Author

costag1982 commented Jan 22, 2025

Image

As you can see I end up with an ID field which is redundant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant