Raddy Website Design & Development Tutorials

Query MongoDB with Custom URL Parameters

By Raddy in NodeJs ·

In this post, I want to show you a very simple example of using custom URL parameters to query data from MongoDB. I am using Mongoose for this example, but we are only going to focus on grabbing the parameters and using the find function to query the data.

Full video and written tutorials are available here.

In the example below we should be able to query the limit, page, category and we can set a custom query using ‘q‘ for short.

An example might be that we want to find Comedy movies and we only want to list two of them:

localhost:5000/api/movies/?category=Comedy&limit=2

/**
* /api/movies/ 
* GET All Movies
*/
app.get('/api/movies/', (req, res) => {
  // Destructing the parameters and giving them a default value
  let { limit = 10, page = 1, category, q } = req.query;

  // Convert Limit and Page to Strings
  // Good for pagination
  const limitRecords = parseInt(limit);
  const skip = (page -1) * limit;

  // Insert everyting into one 'Query' object and check if empty
  let query = {};
  if(q) {
    query = {$text: {$search: q}};
  }
  if(category) query.category = category;
 

  try {
    // Insert the 'Query' object add the Limit Record and Skip
    const movies = await Movie.find(query).limit(limitRecords).skip(skip);
    res.json({ page: page, limit:limitRecords, movies});
  } catch (err) {
    res.status(400).json( {message: err })
  } 
  
})

Thank you for reading this article. Please consider subscribing to my YouTube Channel. It’s FREE!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.