Querying MongoDB, but I can't send the response to the browser

Querying MongoDB, but I can't send the response to the browser
0

I’m working on building an api using Mongoose and Express for storing data on my favorite records. I have the database set up and seeded with data, and I built the skeleton of the Express server. The issue I am having is with the /albums GET route.

I would like the router.get('/albums') function to fetch all the albums from the albums collection, and send a json object to the browser. To do this, I created a getAlbums function, and called it within my route handler. Here’s the code I wrote to do this:

async function getAlbums() {
    // .toArray() didn't solve my problem either
    const albumsQuery = await Album.find().toArray((err, data) => {
        if (err) return console.log(err);
        return data;
    });
    return albumsQuery;
}

When I run console.log(albumsQuery) within the getAlbums() function, I get the following output:

[ { _id: 5dc38170a78ad6389cf87eeb,
    title: 'Nancy Wilson/Cannonball Adderley',
    artist: 'Nancy Wilson',
    year: 1962 },
    {...}, etc...
]

In my /albums route handler, I call getAlbum() and pass it to res.send(), but no matter if I use res.json(), res.send(JSON.parse(getAlbum), or any other data formatting, the data sent to my browser is either an empty object, or an error message. Here’s my current route handler function:

router.get('/albums', (req, res) => {
    let albums = getAlbums();
    res.status(200).send(albums);
});

Can anyone please help me debug this?

Since getAlbums is an asynchronous function, then the second line will not wait for the return value. Trying making the callback function async and putting await before getAlbums(). Since you did not provide a link to your code, I can not test this out, but I think it should solve your problem.

1 Like