Kim Dojin
Kim Dojin

Reputation: 161

Flutter/Dart: save data in different documents in firestore

I am trying to add a data to a firestore with following code.
I select several features such as food, field, date, time, and location. When I press a button Future _addAll function is called and data above are saved into the firestore.

After saving the page moves to main page. The problem starts from here. When I select different data and try to save it to firestore with new documentID, it simply overrides to the previous document unless I refresh the page.

To be specific, when I press the button the data was stored in the document called
-LKV8ZPIAUwk329KqMac. When I selected different data and tried to save to new document, it again was saved in
-LKV8ZPIAUwk329KqMac

Is there a way when I press it saves to a new document each time :) Thank you in advance.

Future _addAll(BuildContext context, List chooseFood, List chooseField, String date, String time,
double latitude, double longitude, String text, String uid, String partnerUid) async {
  _controller.clear(); //clear text message
  var sendRequestID; //variable to store documentID
  List connections = new List();

auth.currentUser().then((user) async { //save data to collection('connect')
await docRef.setData({
  'createdTime': DateTime.now(),
  'foods': chooseFood,
  'fields': chooseField,
  'meet_date': date,
  'meet_time': time,
  'latitude': latitude,
  'longitude': longitude,
  'one_word': text,
}).whenComplete(() {
  sendRequestID = docRef.documentID;
  print("DB 저장 $sendRequestID");
  connections.add(sendRequestID);
}).catchError((e) => print(e));

await docRef.collection('connected_users').document('send_request').setData({ //create collection inside a collection
  'email': user.email,
  'name': user.displayName,
  'photoUrl': user.photoUrl
}).catchError((e)=>print(e));
}

Upvotes: 0

Views: 1954

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126674

You can use collection(...).add(data), which is the equivalent of collection(...).document().setData(data).
This will add a new document. You will have to use this on a CollectionReference.

Upvotes: 1

Related Questions