【问题标题】:type 'ObjectId' is not a subtype of type 'String' of 'value'\'ObjectId\' 类型不是 \'value\' 的 \'String\' 类型的子类型
【发布时间】:2023-02-14 16:58:11
【问题描述】:

我正在尝试使用包 mongo_dart 将文档插入到我的 Mongo 数据库中

  var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  });

第 4 行的运行时错误

Unhandled Exception: type 'ObjectId' is not a subtype of type 'String' of 'value'

是包的问题还是我的代码有问题?

【问题讨论】:

  • 嘿,你解决了吗?我也遇到同样的错误。当我像在 map {} 中那样传递数据时,它正在工作,但我将像 Map<String, dynamic> data 这样的地图变量传递给 insertOne(data)。它给出了错误

标签: mongodb flutter dart


【解决方案1】:

试试这个

var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  }).toList();

【讨论】:

  • insertOne 是一个函数,为什么要把它转成一个列表呢?
【解决方案2】:

您使用的是最新版本的软件包吗?

我认为你的问题与包的 GitHub Repo 中的 issue 有关,但它已于 2015 年 7 月 25 日关闭。

【讨论】:

  • 我正在使用最新版本的软件包,是的。这个问题与我的不同,面临该问题的人似乎正在尝试手动解析 ObjectID,而我只是进行基本插入。
【解决方案3】:

出现错误是因为您在静态connect()异步函数之外声明了变量db和(集合名称);在函数内声明它们。

  var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  });


static connect() async {
var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
   "dateTime": "today",
  });
}

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2020-12-04
    • 1970-01-01
    • 2021-02-05
    • 2021-06-28
    • 2021-01-14
    • 2021-11-07
    • 2021-04-16
    • 2020-12-14
    相关资源
    最近更新 更多