gpt4 book ai didi

mongodb - 两次调用Future后出现NoSuchMethodError

转载 作者:行者123 更新时间:2023-12-03 03:18:52 25 4
gpt4 key购买 nike

我有一个简单的方法,可以从MongoDB中获取一些数据:

import 'package:mongo_dart/mongo_dart.dart';

Future find() {
return _db.open().then((_) {
return _db.collection('foo').find().toList();
}).then((val) {
_db.close();
return val;
});
}

如果我一次调用此方法,它将起作用。连续调用两次将生成 NoSuchMethodError: method not found: 'query'

谁能解释这个问题?

这是完整的堆栈跟踪:
Uncaught Error: The null object does not have a method 'query'.

NoSuchMethodError: method not found: 'query'
Receiver: null
Arguments: [Instance of 'MongoQueryMessage']
Stack Trace:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 Db.queryMessage (package:mongo_dart/src/database/db.dart:174:28)
#2 Cursor.nextObject (package:mongo_dart/src/database/cursor.dart:68:29)
#3 Cursor._nextEach (package:mongo_dart/src/database/cursor.dart:102:15)
#4 Cursor.forEach (package:mongo_dart/src/database/cursor.dart:122:14)
#5 Cursor.toList (package:mongo_dart/src/database/cursor.dart:128:24)
#6 DbConnection.find.<anonymous closure> (package:schafkopfer_server/src/schafkopfer/data.dart:49:52)
#7 _rootRunUnary (dart:async/zone.dart:730)
#8 _RootZone.runUnary (dart:async/zone.dart:864)
#9 _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:488)
#10 _Future._propagateToListeners (dart:async/future_impl.dart:571)
#11 _Future._complete (dart:async/future_impl.dart:317)
#12 Future.forEach.nextElement (dart:async/future.dart:303)
#13 _rootRunUnary (dart:async/zone.dart:730)
#14 _RootZone.runUnary (dart:async/zone.dart:864)
#15 _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:488)
#16 _Future._propagateToListeners (dart:async/future_impl.dart:571)
#17 _Future._completeWithValue (dart:async/future_impl.dart:331)
#18 _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:393)
#19 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:23)
#20 _asyncRunCallback (dart:async/schedule_microtask.dart:32)
#21 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:128)

我打开了 issue for mongo_dart

最佳答案

我相信您在混合异步代码和同步代码,并且在大多数情况下不起作用。

方法find返回Future,但是您尝试在同步模式下第二次调用find
您是否会从find子句中第二次调用then,您的代码将起作用。

main() {
var mongoTest = new MongoTest();
mongoTest.find().then((x) {
print('first find $x');
mongoTest.find().then((x) => print('second find $x'));
});
}

因此mongo_dart Db实例可以在关闭后打开,但在该示例中几乎没有意义。

如果您尝试在Web堆栈的服务器端进行操作,则建议您查看现有框架。例如红石。

http://redstonedart.org/2014/07/14/managing-database-connection-with-redstondart/

关于mongodb - 两次调用Future后出现NoSuchMethodError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com