Retrieve the corresponding value from an object received from express and display it on a jade template

I'm currently working on a solution to display the correct user information on a page when users navigate to "/users/:name". For example, I want to show "welcome user2" if user2 is logged in. My approach involves passing along the parameter from "/users/:name" and checking if it matches the username value. However, I am unsure if this method is secure. How can I iterate through my list of objects and compare them to the parameter?

When I receive this data in my jade document:

{ list: 'userList', users: [ { password: 'pass1', username: 'user1' }, { username: 'user2', password: 'pass2' }, { username: 'user3', password: 'pass3' } ], address: '14459 70th St City NY', desc: '3 floors', __v: 0, _id: 56baf181356641f01213295a }

This data is sent because of the following code:

app.get("/users/:name", function(req, res){
    // console.log(req.params.name)
    User.findOne({"users": { $elemMatch: { username: req.params.name}}}, function(err, doc){
        console.log("test ", doc)
        res.render("users", {result : doc, name: req.params.name});
    })

})

In Jade:

html
    head
    body
        p= result
        p Welcome #{result.users[0].username} #{name} // prints out--> Welcome user1 user2 ||| when user2 signs in
        p= result.address
        h3= result.desc
        a(href="/logout") logout

Answer №1

If you're looking to find the appropriate user object based on the parameter input, consider using this code snippet:

app.get("/users/:name", function(req, res){
    // console.log(req.params.name)
    User.findOne({"users" : { $elemMatch: { username : req.params.name}}}, function(err, doc){
        console.log("test ", doc)
        var users = result.users;
        var currentUser = {};

        for(var i=0;i<users.length;i++)
          if(users[i].username === req.params.name)
            currentUser = users[i];
        res.render("users", {result : doc, user : currentUser });
    });
})

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

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

Implementing custom click event for selecting checkboxes in Material-UI table rows

I have been working with the material-ui data table to implement sorting functionality. One feature I am trying to add is a checkbox on each row. The challenge I am facing is that when clicking on the checkbox, it also triggers the row link, which is not t ...

Is it possible for an ajax request to complete even if a page redirection occurs?

In my current project, I am attempting to generate a temporary URL for a local image and submit it to Google for an Image Search. I need this URL to be transient and automatically deleted after the search is complete. Here's the code snippet that I ha ...

Initiate a POST request to download the file upon clicking the button

How can I initiate a file download when a button is clicked? During testing, I noticed that sending a GET request using <Link href="/api/generate-pdf"> works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the dow ...

What is the method to convert Javascript values from pixels to percentages?

Is it possible to change the scrolltop value dynamically based on a percentage of the user's screen size? I've been trying to achieve this using JS but haven't had any luck. Here is a link to a codepen that showcases the issue: [link] (http ...

Learn how to create a half and half color scheme in an HTML table

I have created an HTML table that resembles a calendar. Various events are registered in the calendar, each distinguished by its color. However, I am looking to change the colors of the cells to be half and half. The image I desire is similar to this: C ...

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

TranslateY animation glitching

I need help with expanding a box to 100% height after click, then collapsing and sticking to the bottom. I created a function in Vue framework to handle the animation, but it's not working smoothly. How can I make it less buggy? Check out the demo her ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...

Launch the jQuery Fancybox on a separate webpage

I am facing an issue where I have a link in my index.html page and I need it to open a div located in another page named index2.html, but for some reason, it is not working. This is the code I currently have: Link in index.html <a href="#modal" id="o ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

Bootstrap form toggle switch component for ReactJS

I'm having trouble figuring out why the default value for my react-bootstrap switch won't set to false (off). It seems like the only way it changes is when I trigger the onChange event handler. Am I overlooking something? Below is the section of ...

Switch between showing and hiding a div by clicking on the panel header and changing the symbol from + to

I need assistance with a panel feature on my website. The panel should expand when the "+" symbol is clicked, displaying the panel body, and the "+" symbol should change to "-" indicating it can be collapsed by clicking it again. There is a slight twist t ...

Executing a JQuery function from varying environments

While this question may seem basic, I am having trouble understanding the behavior described. I have written some JavaScript code and I am puzzled why the second call to foo does not work. You can find the code in this JSFiddle link. $.fn.foo = function( ...

Handling Forms with Node and Express

I'm currently following a guide to create a node/express application using the jade template engine. I've encountered a 404 error when trying to submit a form. In my routing, I have this line: app.post('sign_up', sign_up); which is caus ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...