Anonymous
Anonymous

Reputation: 383

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.

Upvotes: 1

Views: 1671

Answers (3)

Lukas David
Lukas David

Reputation: 143

Try this:

(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);
        });
})();

first param of your callback is error wich is null, the rest is self explanatory

Upvotes: 0

codeguy
codeguy

Reputation: 126

.find() returns a cursor so you can always use .next(callback) and any of the other cursor methods to return an array of returned results.

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

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

     console.log(resultArray);

});

Upvotes: 0

Anonymous
Anonymous

Reputation: 383

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);
    });

Upvotes: 1

Related Questions