Mongo dart insert element in list

Issue

I’m trying to insert an element in a mongoDB list. I’m using flutter and the package mongo_dart.

This is the call that I’m performing:

await usersCollection.modernUpdate(
  where.eq('_id', userService.currentUser.id), 
  modify.addToSet('favorites', favorite)
);

The problem is that if I pass a string instead of favorite it works. But if I pass a custom object like favorite I’m retrieving this error:

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Exception: Not implemented for Instance of 'Favorite'
#0      new BsonObject.bsonObjectFrom
package:bson/src/bson_type.dart:157
#1      BsonObject.elementSize
package:bson/src/bson_type.dart:206
#2      BsonMap.dataSize.<anonymous closure>
package:bson/…/types/map.dart:27
#3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#4      BsonMap.dataSize
package:bson/…/types/map.dart:26
#5      BsonMap.byteLength
package:bson/…/types/map.dart:36
#6      BsonObject.elementSize
package:bson/src/bson_type.dart:206
#7      BsonMap.dataSize.<anonymous closure>
package:bson/…/types/map.dart:27
#8      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)

I’m not understanding since favorite is instanced.

Solution

I found a solution.

Just pass the data as a json.

await usersCollection.modernUpdate(
  where.eq('_id', userService.currentUser.id), 
  modify.push('favorites', {"id": id, "data": DateTime.now()})
);

Answered By – carlo97

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *