Route.param query triggered callback

I have a set of routes on my server for retrieving post information and media:

// Retrieve post information (description and tags)
router.get('/:post_id/information', function(req, res) {
  User.findById(req.params.post_id)
      .select('data.title.text tags')
      .exec(function(req, post) {

    res.json(post);
  });
});

// Retrieve post media object
router.get('/:post_id/media', function(req, res) {
  User.findById(req.params.post_id)
      .select('data.media')
      .exec(function(req, post) {

    res.json(post);
  });
});

I wanted to create a callback trigger for the route parameter post_id:

// Handle 'post_id' parameter - executed for every route
router.param('post_id', function(req, res, next, post_id) {
  Post.findById(post_id, function (err, post){
    if(err) { throw err; }

    // If no post is found
    if(!post) {
      return res.status(404).send({ message: { post: 'There is no such post.'} });
      // Something went wrong! The requested post does not exist.
    }

    req.post = post;
    return next();
  });
});

After executing this callback trigger, I needed to continue with different queries based on the route. Is there a way to achieve this? I initially tried using req.post instead of User.findById(), but that didn't work as expected since req.post stores the result from the initial query.

Answer №1

In order to include additional routes, you can use an if statement like this:

// This code is associated with the parameter 'timeline_id' and will be executed for each route
router.param('post_id', function(req, res, next, post_id) {
  Post.findById(post_id, function (err, post){
    if (err) {
      return next(new Error("Unable to locate user: " + err));
    }

    // If no post is found
    if(!post) {
      return res.status(404).send({ message: { post: 'There is no such timeline.'} });
      // An error occurred as the requested timeline does not exist.
      next();
    }

    req.post = post;
    next();
  });
});

View more information here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Webstorm 7 for Mac OSX is having trouble generating a Node.js Express App

Trying to develop a Node.JS app using the express framework in Webstorm 7 has been challenging. I keep encountering this error: https://i.stack.imgur.com/BzruH.png I suspect it may be related to permissions or the NPM route, but I am unsure how to make a ...

Learn how to update a fixed value by adding the content entered into the Input textfield using Material-UI

I made a field using the Input component from material-ui: <Input placeholder="0.00" value={rate} onChange={event => { this.setState({ `obj.rate`, event.target.value }); }} /> Whenever I input a rate into this field, ...

Learn how to utilize the import functionality in Node.js by importing functions from one .js module to another .js module. This process can be seamlessly integrated

Hey there! I'm currently facing a challenge where I need to import a function from one JavaScript file to another. Both files are on the client side in Node.js, so I can't use the require method. If I try to use the import statement, I would need ...

Incorporating images from local storage into hero cards

I'm attempting to use images that are stored in my project directory as the images for my hero cards. However, it doesn't seem to be working. Is it only possible to include images on hero cards from a URL? Thanks Updated Solution: var image64 = ...

Generate diagrams for Node.js classes

Hello there! I attempted to implement Wavi for a Node.js project in order to create a class diagram. Everything seems to be set up correctly with the path variable and Graphviz installation, but I'm still facing some issues. Can anyone offer any guida ...

What is the best approach for managing CNAME records during domain resolution?

When my web application receives an unfiltered string from an untrusted user, it must determine whether this string, when used as a hostname, resolves to an IPv4 or IPv6 address within a forbidden range specified by predefined rules. If the string appears ...

Guide to incorporating external proto definitions into NodeJS using proto-loader

The URL for making RPCs is flow-testnet.g.alchemy.com:443 I am currently missing all .proto files on my local system. What is the process for loading them in order to create package definitions? ...

Having difficulty grasping async operations in nodejs when executing sqlite3 queries, as the queries

It seems that I may be unintentionally neglecting to consider async functionality when writing my code. Unfortunately, I am unsure of how to properly implement it. // order.xml const db = require("./db"); let orders = db.getNewOrders(); console.log(order ...

When loading a page with Puppeteer using the setContent method, images may not be loaded

Currently, I am experiencing an issue with Puppeteer where it does not load resources that are specified with relative paths (such as background.png in the image src or in CSS url()). When I try to load the content of a local file using setContent(), the o ...

What are the steps to initiate a new project using the CLI on a Linux operating system

I've got a project up and running in Vue JS with Node JS installed. Now I want to create a new project using CLI. Do I need to install another version of Node JS for this new project? ...

Using database entries to generate dynamic routes in express.js without the need for a server restart

I have created a custom Express instance for my KeystoneJS v5 app that serves data stored in a Postgres database with the following model: CREATE TABLE "Link" ( id integer DEFAULT PRIMARY KEY, customer text, slug text ); I've set up dyna ...

Is there a way to retrieve a collection of files with a particular file extension by utilizing node.js?

The fs package in Node.js provides a variety of methods for listing directories: fs.readdir(path, [callback]) - This asynchronous method reads the contents of a directory. The callback function receives two arguments (err, files), with files being an arra ...

The EC2 instance faced a prolonged delay and rejected the connection attempt

Good day to all, I'm seeking assistance with an issue I've been encountering while attempting to host a test project on AWS EC2. Despite following the recommended procedures from tutorials and properly configuring ports and security groups, the ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Why is my Node.js express application throwing a 404 POST error?

I am facing an issue while trying to build a node.js application with express. Whenever I attempt to log in and my index.ejs file sends a post request to the server, I encounter a 404 error. Being new to programming, I am seeking assistance from someone wh ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Exploring Passport.SocketIo: A Guide to Retrieve a Roster of Active Users Using NodeJS, Express, and Passport

After successfully setting up the sessionStore with MongoStore, every login is functioning properly and sessions are being securely written to the database without any errors. To integrate Passport with Socket.IO, I am utilizing the package available at gi ...

Utilizing the Twitter API with Next.js to automate tweets even when the website is not actively engaged

Currently, I am utilizing next.js for the development of a web application. My goal is to have this app automatically post to my Twitter account. I have already set up a developer account on Twitter and an API in nextjs. By calling the API, it will trigger ...

I have the latitude and longitude for both the shop and user, and I am looking to display a list of shops in order based

Currently, I have the latitude and longitude for both my shop and the user. My objective is to display a list of shops that fall within the geographic area between the user's location and the shop's coordinates using Sequelize ORM. Can you provid ...

Ways to retrieve directory information in Next.js hosted on Netlify

Having trouble retrieving a list of directories in Next.js on Netlify. The code works fine on localhost, but once deployed to Netlify, an error is triggered: { "errorType": "Runtime.UnhandledPromiseRejection", "errorMessage": ...