mongo-dart / mongo_dart

Mongo_dart: MongoDB driver for Dart programming language
https://pub.dev/packages/mongo_dart
MIT License
446 stars 98 forks source link

What function can I get the `String` in `ObjectId` when using `find()`? #306

Closed SittiphanSittisak closed 1 year ago

SittiphanSittisak commented 1 year ago

I want to replace the '_id' value (ObjectId) with the ObjectId.$oid. I am using:

List<Map<String, dynamic>> data = await mongodb.dbCollection.find().toList();
      for (var i = 0; i < data.length; i++) {
        data[i]['_id'] = (data[i]['_id'] as ObjectId).$oid;
      }

but this looks like not good practice. Are there any functions in find() to solve it?

giorgiofran commented 1 year ago

You canno substitute the _idfield, once assigned it cannot be changed. You have to create a new record with the same data and the new key and delete the old one.

SittiphanSittisak commented 1 year ago

Hi @giorgiofran, I want to send data via an API with the Map that contains { '_id' : (data[i]['_id'] as ObjectId).$oid } (the value type is String) not { '_id' : data[i]['_id'] } (the value type is ObjectId). (Not change data in the database) At the moment I must use a loop to change this. Is any way without using a loop?

  List<Map<String, dynamic>> selectionList = await mongodb.selectionDbCollection
      .find(where.fields(['value']))
      .map((event) {
    event['_id'] = (event['_id'] as ObjectId).$oid;
    return event;
  }).toList();
giorgiofran commented 1 year ago

I'd do the same way you did.

SittiphanSittisak commented 1 year ago

Thank you @giorgiofran . This clear.