0

I'm currently building a REST API using Node.js with Express.js and I'm quite new to this technology. The following code shows the get method to a list of councils stored in MongoDB.

const { Council } = require('../mongoose-models/council');
const express = require('express');
const router = express.Router();

router.get('/', async (req, res) => {
  const query = req.query;
  const councilsList = await Council.find(query);

  if (!councilsList) return res.status(404).send('No councils found.');
  res.send(councilsList);
});

module.exports = router; 

From my previous experience when developing REST API using java, I can customise different queries by implementing different methods with their own paths. For example:

@Path("findByCouncilName/{councilName}")
@Path("findCouncilsNotInMyArea/{longitude}/{latitude}")

And within each method, I can then write different logics. However, in Express.js, it seems that I have to implement all these different logics into one block. It seems not flexible and how can actually implement it? Furthermore, does the query must be same as the key name in MongoDB? What if I want to filter the results based on a specified index element in a nested array in a document?

1

3 Answers 3

2

For your routes:

@Path("findByCouncilName/{councilName}") @Path("findCouncilsNotInMyArea/{longitude}/{latitude}")

If you are to implement them in express, you can split them into different blocks actually.

Instead of listening to '/' and try to handle everything inside, you can try this.

const express = require('express');
const router = express.Router();

router.get('/findByCouncilName/:councilName', async (req, res) => {
  const councilName = req.params.councilName;

  // Your logic goes here

  res.send();
});

router.get('/findCouncilsNotInMyArea/:longitude/:latitude', async (req, res) => {
  const longitude = req.params.longitude;
  const latitude = req.params.latitude;

  // Your logic goes here

  res.send();
});

module.exports = router; 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use it like lets say:

router.get('/:councilName', async (req, res) => {

Then use the parameter in the route with :

req.params.councilName

Comments

0

Express doc is your friend

https://expressjs.com/en/guide/routing.html

Here is everything you should know about express routing. You can specify individual logic for every pat-method pair, and again, use general as needed.

You need to be aware of path order in which Express resolves them, eg. first path to match will will be executed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.