DEV Community

Cover image for Mastering The Database - Node.js, Express.js, MongoDB - Series #09
Functional Javascript
Functional Javascript

Posted on

Mastering The Database - Node.js, Express.js, MongoDB - Series #09

Intro

Let's retieve some random items from a database collection

app.post(apiEnum.api_find_artists_random, async (req, res) => {
  res.json(await mgArr(dbEnum.nlpdb, collEnum.songsColl,
    randomSample(50),
  ));
});

Enter fullscreen mode Exit fullscreen mode

Notes

1.
We are using MongoDB's aggregation framework to retrieve a random sample of artists.

2.
This query has one aggregation stage, called "randomSample", which is just a functional wrapper around the $sample stage operator:

/**
@func
retrieve a random sample of docs

@param {number} lim
@return {object}
*/
export const randomSample = lim => ({ $sample: { size: lim } });
Enter fullscreen mode Exit fullscreen mode

3.
Notice our query is already wrapped in an Express Route. Any registered client call that hits that route will retrieve the results.

Client Call

Here is our client call:

const fetchArtistsRandom = async () => {
 const r = await fetchArrNoParams(apiEnum.api_find_artists_random);
// ...
};
Enter fullscreen mode Exit fullscreen mode

Client Call Notes

1.
Notice the custom fetch wrapper func.

2.
The "NoParams" portion of the name means we do not pass up any parameters to the server.

3.
the "fetchArr" means it returns an arr of results. (as opposed to just a single doc, which is called fetchObj).

4.
Notice we pass in only the URL segment of the API. This fetch wrapper func will retrieve the server base url. This url is set at build time. The build tool will modify the config file with the proper base url to the server.

5.
The fetch wrapper func will call axios using the POST method. All calls use the POST method to avoid the disadvantages associated with the passing of data over the URL.

6.
The fetchArtistsRandom event handler func can be called from the onMount lifecyle func, or from a wired up click event.
eg:

on:click={fetchArtistsRandom}
Enter fullscreen mode Exit fullscreen mode

Example UI Display

Random Artists example

What's next

Here we've shown an example querying data from an API Route, from the User Interface.
It takes just a matter of a minutes to set up a query for the User Interface once you have a set of tools in place.

If you have any questions, let me know.

Resources

Select random items using the $sample stage operator:
https://docs.mongodb.com/manual/reference/operator/aggregation/sample

Top comments (0)