1

I have tried to store a Map of data with set method, but everytime it overwrites the data in firebase. With update method setting that same Map of data works, it does not overwrite, but creates a new array and stores it.

enter image description here

I want to store the location entry data in this format. How can I achieve that with set method not with update method, cause update method requires a collection and document to already exist, but in my case they will be automatically created based on uid of the logged in user.

Here is my code for the Map and sending data to firebase.

uploadLoacationEntryData(
  locationName, fullAddress, visitTime, visitDate, entryDate) async {
Map<String, dynamic> locationMap = {
  "locationName": locationName,
  "fullAddress": fullAddress,
  "visitTime": visitTime,
  "visitDate": visitDate,
  "entryDate": entryDate,
};
//await _locationEntryDA.setUserLocationEntry(locationMap);
await _locationEntryDA.updateUserLocationEntry(locationMap);}



Future setUserLocationEntry(locationMap) async {
return await _firestore
    .collection("LocationEntry")
    .doc(_auth.currentUser.uid)
    .set({
  "locationEntry": FieldValue.arrayUnion([locationMap])
});}



Future updateUserLocationEntry(locationMap) async {
return await _firestore
    .collection("LocationEntry")
    .doc(_auth.currentUser.uid)
    .update({
  "locationEntry": FieldValue.arrayUnion([locationMap])
});}

1 Answer 1

1

It sounds like you're looking for the set-and-merge operation, which in Flutter would look like:

docRef.set(
  { "locationEntry": FieldValue.arrayUnion([locationMap])}, 
  SetOptions(merge : true)
)
Sign up to request clarification or add additional context in comments.

3 Comments

It merges the new field values you specify with any existing fields. So it essentially does the same as an update(), but by using set() it will also create the document if it doesn't exist (which I think is what you asked for). Did you try the code yet? If it didn't do what you wanted, can you show what you did, what happened, and what you expected to happen?
Thank you for your answer! It worked successfully.
And yes, also thank you for your explanation, this is what I wanted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.