Search code examples
node.jsmongodbmongoosegridfs

Mongodb find().toArray() returns null


I am struggling to find why this doesn't work. All I want to do is to get the data from a collection.

(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 just returns null.

I've been stuck with this issue for 2 days now and its just frustrating why this doesn't work. Am I missing a piece? Is the syntax different when working with GridFS?

And yes there is data in the database. When I use bucket.openDownloadStream(id) it works completely fine.


Solution

  • Turns out toArray doesnt return a callback (even though it says so in the docs). Either way just use promises.

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