Mongodb find().toArray() returns 空

Mongodb find().toArray() returns null

我正在努力寻找为什么这不起作用。我只想从集合中获取数据。

(async () => {
    try {
        await mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true });
        const { db } = mongoose.connection;
        const bucket = new mongoose.mongo.GridFSBucket(db);

        const file = bucket.find().toArray(i => {
            console.log(i);
        });
})();

console.log 只是 returns 空。

我已经被这个问题困扰了 2 天,令人沮丧的是为什么这不起作用。我错过了一块吗?使用 GridFS 时语法是否不同?

是的,数据库中有数据。当我使用 bucket.openDownloadStream(id) 时,它完全可以正常工作。

事实证明 toArray 没有 return 回调(即使它在文档中这么说)。无论哪种方式,只需使用承诺。

    const file = bucket.find().toArray().then(i => {
        console.log(i);
    });

.find() return 是游标,因此您始终可以使用 .next(callback) 和任何其他游标方法来 return 一个 returned 结果数组.

http://mongodb.github.io/node-mongodb-native/3.5/api/Cursor.html#next

const file = bucket.find().next(function(resultArray) {

     console.log(resultArray);

});

试试这个:

(async () => {
    try {
        await mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true });
        const { db } = mongoose.connection;
        const bucket = new mongoose.mongo.GridFSBucket(db);

        const file = bucket.find().toArray((e, i) => {
            console.log(i);
        });
})();

回调的第一个参数是 error wich 为 null,其余参数不言自明