Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to get the newly created document when posting a new item into firestore.

I know there are other similar questions and I tried them! BUT not getting the output that I was hoping for.

So basically, I set a bunch of data and then I do doc().id within then and it returns an id that does not exist in my firestore nor does it match any of my created documents.

code:

return _userRef.doc(_user.uid).collection(collName).doc().set({
      'item_name': name,
      'item_description': description,
      'item_location':
          GeoPoint(_locationData.latitude, _locationData.longitude),
      'item_date': DateTime.now(),
      'item_images': imageMap,
    }).then((value) {   
      print('${_userRef.doc(_user.uid).collection(collName).doc().id}');
    });

I saw another question where they did :

 var ref = _userRef
              .doc(_user.uid)
              .collection(collName)
              .get()
              .then((value) => print('hello ***** ${value.docs[0].id}'));

but this just returns the first document in the list of documents! I was thinking of loading one array before the set and then load a 2nd array after the set and then just compare the 2 arrays and find the odd man out. BUT that would take a very long time if I have a huge list!

Any thoughts??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
594 views
Welcome To Ask or Share your Answers For Others

1 Answer

doc() with no parameters creates a DocumentReference with a random ID. If you want to know that ID, it's immediately available in that object's id property. You can access it right away without having to write anything.

var ref = _userRef.doc(_user.uid).collection(collName).doc();
print(ref.id);

The ID is generated in the client app, which is why it's immediately available. The document won't actually exist until you call set() on that reference.

ref.set(...);  // after success, the document will exist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...