我正在使用带有 typescript 的 Visual Studio。这段代码中的所有内容都会编译。根据the mongoDB docs我正确使用了 toArray 。我对 typescript 有点陌生,所以我不知道这是 typescript 错误还是mongodb。 tests
变量似乎有一个方法toArray
,但当我调用它时没有任何返回。 console.log
调用甚至没有跑。根据文档和 typescript samples这是正确的做法。任何人都可以与我分享我的代码中的任何错误,或者“正确”的方法吗?
///<reference path="c:\DefinitelyTyped\mongodb\mongodb.d.ts"/>
import mongodb = require("mongodb")
var server = new mongodb.Server('localhost',27017, { auto_reconnect: true})
var db = new mongodb.Db('test', server, { w: 1 });
export interface Test {
_id: mongodb.ObjectID;
a: number;
}
db.open(function () { });
export function getTest(callback: (test: any) => void): void {
db.collection('test', function (err, test_collection) {
// test_collection.find().toArray -- this doesn't work either
test_collection.find(function (err, tests) {
console.log(tests, 'from getTest') // log's an object with `toArray` method
tests.toArray(function (err, docs) { // nothing returned. Seems like the callback isn't ran
if (err) { console.log(err) }
console.log(docs, 'from toArray')
callback(docs)
})
})
})
}
最佳答案
您的问题似乎是没有将您的函数放在 db.open
方法的回调中:
var mongodb = require("mongodb");
var server = new mongodb.Server('localhost', 27017, { auto_reconnect: true });
var db = new mongodb.Db('test', server, { w: 1 });
db.open(function() {
db.createCollection('test', function(err, collection) {
collection.find().toArray(function(err,docs) {
console.log( docs );
});
});
});
在执行任何操作之前,您通常需要确保连接已打开
关于javascript - mongodb 与 typescript `toArray` 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22688462/