Home > Back-end >  mongo_dart error: A value of type 'Rational' can't be assigned to a variable of type
mongo_dart error: A value of type 'Rational' can't be assigned to a variable of type

Time:10-04

The code below tries to create a Dart server and open a Mongo database. When database section below is commented, then the server starts as expected. Uncommenting the database section dumps the below error on console.

../../.pub-cache/hosted/pub.dartlang.org/bson- 
2.0.1/lib/src/types/decimal_128.dart:36:58: Error: A value of type 'Rational' can't 
be assigned to a variable of type 'Decimal'.

Environment: MacOS_x64 12.6, Dart SDK version: 2.19.0-264.0.dev (dev)

import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:mongo_dart/mongo_dart.dart';

// Configure routes.
final _router = Router()
 ..get('/', _rootHandler)
 ..get('/echo/<message>', _echoHandler);

Response _rootHandler(Request req) {
  return Response.ok('Hello, World!\n');
}

Response _echoHandler(Request request) {
  final message = request.params['message'];
  return Response.ok('$message\n');
  }

void main(List<String> args) async {
  // Use any available host or container IP (usually `0.0.0.0`).
  final ip = InternetAddress.anyIPv4;

  // Configure a pipeline that logs requests.
    final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);

    // For running in containers, we respect the PORT environment variable.
    final port = int.parse(Platform.environment['PORT'] ?? '8080');
    final server = await serve(handler, ip, port);
    print('Server listening on port ${server.port}');

    ///  Database Section  ///
    final db = Db('mongodb://localhost:27017/testdb');

    try {
      print('Opening database\n');
      await db.open();
      print('database connected');
      print('Database connected');
    } catch (e) {
      print(e);
      exit(0);
    }
  }

enter image description here

CodePudding user response:

It would seem that the bson package is to blame for the error. I would post an issue ticket on their repository detailing this issue, and also post an issue on the mongo_dart package bringing it to their attention. Perhaps they are using an outdated version of the decimal or rational package. (Or maybe this has already been fixed in the bson package and it's the mongo_dart package that needs to update its dependencies.)

Per the documentation, Decimal.pow returns a Rational, and Decimal and Rational are not directly compatible types. They would need to use the extension method Rational.toDecimal to convert the value back to a Decimal.

// For example
final Decimal maxUint64 = Decimal(2).pow(64).toDecimal();
  • Related