我正在用Flutter和MongoDB构建一个应用程序。有一件事我不明白。
当我检索用户数据时,我通过将Map<String, dynamic>?变量传递给函数fromJson来设置我的对象。
问题是,id得到了mongo的所有语法,比如:ObjectId("62096f5cbbf77abdf2ee00e4"),我只希望"62096f5cbbf77abdf2ee00e4"有一个更干净的语法。
这有可能吗?
User.fromJson(Map<String, dynamic> json) :
id = json['_id'].toString(),
name = json['name'].toString();用解决方案编辑
我认为最好的解决方案是使用来自mongo_dart ObjectId的自定义类型来保存id。
发布于 2022-10-21 14:05:50
_id是ObjectId。
ObjectId objectId = collections.first['_id'];
print("objectId: ${objectId.id}");
print("oid: ${objectId.$oid}");
print("dateTime: ${objectId.dateTime}");
print("hashCode: ${objectId.hashCode}");结果如下:
objectId: BsonBinary(62096f5cbbf77abdf2ee00e4)
oid: 62096f5cbbf77abdf2ee00e4
dateTime: 2022-10-21 00:00:00.000
hashCode: 123456789你想要$oid。我想你可以改变这条线
id = json['_id'].toString(),至
id = json['_id'].$oid.toString(),
//or
id = (json['_id'] as ObjectId).$oid.toString(),https://stackoverflow.com/questions/71241748
复制相似问题