2

I have a Map object in my document data. Like Below

enter image description here

I have to add a new user bid to the same map without erasing old data but the code I used was replacing the whole Map with the new value. Any suggestions on how to achieve my goal.

FirebaseFirestore.instance.collection('products')
.doc(widget.product.uid).update({
  'bids': {
  auth.currentUser?.email:
      currentPrice.toString()
  }
});
2
  • Ok that means, I have to update Map myself and then add it to firestore. Is it ? Commented Jul 18, 2021 at 7:39
  • Ok thanks for the help😊 Commented Jul 18, 2021 at 7:43

1 Answer 1

8

You need to use dot notation to update a nested field:

const userEmail = auth.currentUser?.email;
FirebaseFirestore.instance.collection('products')
.doc(widget.product.uid).update({
  'bids.${userEmail}':  currentPrice.toString()
});

Dot notation allows you to update a single nested field without overwriting other nested field. If you update a nested field without dot notation, you will overwrite the entire map field

References:

  1. Update fields in nested objects
  2. FlutterFire Documentation

To update fields with . in their keys:

var fPath = FieldPath(["bids", "[email protected]"]);
FirebaseFirestore.instance.collection('products').doc(widget.product.uid).update(fPath, currentPrice.toString());
Sign up to request clarification or add additional context in comments.

6 Comments

Definitely more efficient than my solution. Use this
@MadduSwaroop can you share your updated code? Also try restarting your emulator or app. Using dot notation should update that field only and not overwrite others. It's mentioned in both Firebase's docs and FlutterFire's.
Sorry I forgot to save : ) My bad.
You are simply awesome Thanks for the help.
Bro this time another map was creating inside bids because of . in mail id? Any way to avoid it
|

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.