| 0 | kirasiris | Categories: Tags: , , , ,


Have you heard about the MVC pattern in high-tech frameworks? Well if you don’t….this is what it means: Model-View-Controller. The M(Model) is the file in which you handle the connection between the DB and your application; V(View ) is what you see in front of you which most of the times contains some dynamic data; C(Controller) is where most of the complexity of any application and yours, lives. MERN works similarly to the MVC pattern; thus making it easy to learn.

In order to follow this post, you should already have a MongoDB account created and a connection between your application and the database. If by any chance you don’t know how to do this, I recommend you to read the following website and learn more about it at MongoDB Tutorial. Once you have done that, please feel free to use the code found below.

Working with data coming from any database is easy but sometimes the learning curve can be a challenge. In order to make it easy for you, I decided to post an example of how to fetch data from MongoDB, specifically when you want it to sort it out by some field. In the code below the query is easy, it fetches the data by sorting it out by the date field. See below:

// @route       GET api/secrets
// @description Get all secrets
// @access      Public
router.get('/', async (req, res) => {
  try {
    const secrets = await Secret.find().sort({ date: -1 });
  } catch (err) {
    res.status(500).send('Server error');

There are several ways to sort out data but the most used one are by date as shown  above and by id. You can also fetch data more specifically, let’s say, there is a field with the name of status ; this field can have several options such as active, inactive and banned. In order to fetch the desired data by having status equal to active, you would have to create something like find({inputField = 'active'}) in your query.

That is it. Don’t forget to share this post about MERN if you found it useful.

Leave a Reply

Back to Top