Creating Unique Identifiers in ExpressJS

I am currently utilizing mongoose to display admin and user information on a dashboard, but I am encountering difficulty rendering the id of a user. Below is the code I am using:

function ensureAuthenticated(req, res, next){
  if(req.isAuthenticated()){
    return next();
  } else {
    req.flash('error_msg', 'You are not logged in');
    res.redirect('/dashboard/login');
  }
}

/* GET Dashboard page. */
router.get('/dashboard', ensureAuthenticated, (req, res) => {
  User.find({}, function(err, users) {
    res.render('dashboard/index.hbs', {
      pageTitle: 'Dashboard',
      total: users.length,
      users: users
    });
  });
});
<a href="/dashboard/users/{{_id}}">My profile</a>

I have added some code to the question from the repository, including the ensureAuthenticated function. Based on my observation, the model and everything else seem to be set up correctly. For example, the total renders correctly, indicating that it is receiving users data as well.

Answer №1

If you take a closer look at the req object, you'll notice that something, possibly Passport, has directly included a user variable. This means you can easily pass that information into your view.

/* GET Dashboard page. */
router.get('/dashboard', ensureAuthenticated, (req, res) => {
  User.find({}, function(err, users) {
    res.render('dashboard/index.hbs', {
      pageTitle: 'Dashboard',
      total: users.length,
      users: users,
      currentUser: req.user
    });
  });
});

In your view, you can access this user information like this:

<a href="/dashboard/users/{{currentUser._id}}">My profile</a>

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

The jQuery closest selector seems to be malfunctioning when trying to scroll and focus on a specific class

My HTML code snippet is as follows: <div class="main"> <div class="sub-1"> <select> <option>1</option> <option>2</option> </select> </div> <div class="sub-2"> ...

What is the correct way to establish an array variable containing objects?

What is the correct way to declare an object within an array variable? I encountered the following error message: "TypeError: Cannot set property 'name' of undefined" Here is the code snippet in question: let data = [] data[0].name = "john" ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Reordering a pair of items within an array using ReactJS

After pondering, I wondered if there exists a neat and tidy method to swap two objects within an array while utilizing setState. Here's my current approach: export function moveStepUp(index) { if(index > 0){ let currentStep = this.stat ...

custom dialog box appears using ajax after successful action

Recently, I created a custom dialog/modal box with the following code: <div id="customdialog" class="modal"> <div class="modal__overlay"></div> <div class="modal__content"> <h2><strong>Hello</strong&g ...

I'm looking to retrieve the selected value from my autocomplete box in React using the Material UI library. How can I

Here is a snippet of code that utilizes an external library called material ui to create a search box with autocomplete functionality. When a value is selected, an input tag is generated with the value "selected value". How can I retrieve this value in ord ...

What is the best way to synchronize the state of a single React component across various pages?

I am currently working on a React Component that includes a toggle feature (on or off) with the state being managed by the component's own state (this.state). My dilemma is ensuring that this state remains when the user navigates from one page to ano ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

the navigate feature is not redirecting to the intended page as expected

I am currently working on a React application and facing an issue with configuring the navigation. The problem lies in the code of the Navbar component, where upon clicking the logout button, the authentication context should be cleared and the user should ...

Utilize map() and concat() in JavaScript for more streamlined code - a tidier approach

Is there a way to optimize the code below by combining map() and concat() for efficiency? const firstColumnData = data.map((item: any) => { return item.firstColumn; }); const secondColumnData = data.map((item: any) => { return item.secondColumn; } ...

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...

Tips for effectively managing pagination in a Node.js application

I am currently working with the ORM sequelize and a postgresql database, and I am looking to incorporate pagination into my project. When using a MongoDB database, pagination can easily be achieved as shown below: module.exports.getBySprOilfieldId = async ...

The value from the textbox is not being received by the JavaScript and PHP

I'm encountering an issue with my codes where they are not properly passing the value of the verification code from the textbox to JavaScript and then to PHP. I need assistance in resolving this issue. Below is the snippet of code: HTML: /* HTML c ...

Incorporate a collection of product titles along with their short forms in JavaScript/jQuery

Seeking guidance as a newcomer to JS. I have encountered the need for two different views in an application I am working on - one displaying full product names and the other showing only their abbreviations. Instead of hard-coding this information, I wish ...

When attempting to reference from a variable, you may encounter an error stating that setAttribute

In my VueJS project, I am facing an issue with dynamically adding the width attribute to an inline SVG code stored in a variable called icon. Despite having the correct SVG icon code in the variable, the setAttribute method is not working as expected and t ...

Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example: function onExit(){ localStorage.setItem("my_object","'" + JSON.stringify(object) + "'"); } When retrieving this data from localStorage, it may loo ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...

Implement a dynamic table in real-time with jQuery AJAX by fetching data from JSON or HTML files

Hey @SOF, I'm trying to add an auto-update feature to my school grades webpage using jquery and ajax to refresh the data when new information is available. I also want to create a "single view" for classes. The challenge I'm facing is getting t ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Unable to access local JSON file data in React.js

I have been struggling to retrieve data from a JSON file located within my ReactJS project directory. Even attempting to access the package.json file within the ReactJS folder resulted in errors. How can I successfully extract data from a local JSON file ...