Im reading the firestore flutter sdk documentation. It shows how to use a serializable class to automatically convert documents to objects with this example:
class Movie {
Movie({required this.title, required this.genre});
Movie.fromJson(Map<String, Object?> json)
: this(
title: json['title']! as String,
genre: json['genre']! as String,
);
final String title;
final String genre;
Map<String, Object?> toJson() {
return {
'title': title,
'genre': genre,
};
}
}
and then create a new document using the add function:
await moviesRef.add(
Movie(
title: 'Star Wars: A New Hope (Episode IV)',
genre: 'Sci-fi'
),
);
How would I get the documentId after adding a new document or when querying?
2
Answers
I tried to achieve a behavior like this before, in Firebase Firestore, either you call
moviesRef.add()
then firebase will add a new document with a completely auto-generated uid, or if you’re having a specific uid then you can just use themoviesRef.doc(hereTheId).set()
.However , the
moviesRef.add()
returns aDocumentReference
which you can get from it the is like this example:using then:
.then((val)=> print(val.documentID)});
using await/async:
You can also get a completely auto-generated uid before sending the request , then call
moviesRef.doc(hereTheId).set()
like this:Hope this helps.
I think we also need to manipulate the Ref to be able to use like you mentioned above with add method, which will get the
Future<DocumentReference> add(Movie data) Returns a DocumentReference with an auto-generated ID, after populating it with provided data.
As shown in here like following:
And while adding it you need added document id you can achieve it like this :