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

Vue.js seems to be leading me down a long and steady path of progress at a snail

I've exhausted all efforts to resolve the file paths for Home and App. I even turned to AI to help me out, but still no luck. Code snippet from main.js in the src folder: import Home from '@views/Home.vue'; // Using alias import App from ...

Embed a variable into an HTML element without affecting the inner HTML content

I am trying to inject a specific string into an HTML tag <td anyElement="{{myString}}" >some random text here </td> My desired interpretation is as follows: <td anyElement='Some string'>some random text here </td> Howe ...

Error occurs when attempting to filter data through input text pasting in Angular

Currently, I am working on a web application that utilizes the Angular framework and angularfire2. The issue I am encountering is related to the data filter functionality not functioning correctly when pasting copied text. Interestingly, it works perfectly ...

What causes discrepancies between jQuery set attributes and .html() output?

In an attempt to set attributes on HTML snippets, I am aiming to repopulate a form with previously entered values. Despite using .attr() to set the attributes, they do not appear after using .html(). For reference, I have provided a simple example here: h ...

Switch on and activate a button using AngularJS

I have a set of four buttons that I want to toggle and activate upon clicking them. Currently, the buttons toggle when double-clicked. My desired solution is for the button current btn to be highlighted and display data when clicked, and for the previous ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

I have created a textbox with a button, but I am unsure of how to delete it

var emailFields = document.getElementById('emails'), addLinkButton = document.createElement('a'), fieldTemplate = emailFields.getElementsByTagName('div'), currentFieldCount = fieldTemplate.length, maxFields ...

Exploring the dynamics of Django, Webpack, and Vue with the added feature of code splitting: A guide to customizing chunk

I am currently using Django in conjunction with Webpack and Vue, as well as implementing Code splitting within Webpack. The issue I am facing is that Webpack splits chunk files from the source code of .vue files, but I am unable to load these chunk files i ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Is there a way to verify if the JSON Object array includes the specified value in an array?

I am working with JSON data that contains categories and an array of main categories. categories = [ {catValue:1, catName: 'Arts, crafts, and collectibles'}, {catValue:2, catName: 'Baby'}, {catValue:3, catName: 'Beauty ...

What is the best way to monitor a variable using the controllerAs syntax in Angular?

When utilizing the standard controller syntax in AngularJS, you have the ability to watch a variable with code like this: $scope.$watch(somethingToWatch, function() { alert('It changed!'); }); However, with the controllerAs syntax, how can I ea ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Exploring VueJS watchers: How to get started?

Struggling to grasp the concept of Watchers in VueJS, particularly when trying to implement them for tracking tab changes and resetting values. Even though I have set up a watch with parameters like `oldValue` and `newValue`, their usage remains unclear to ...

Combining Typescript Declarations for Express Request Object with Passport.js User/Session Integration

In my express/nodejs app, I am encountering issues with properties on the request.user object even after implementing Declaration Merging for authentication using passportjs middleware. To address this, I created a file at /types/index.d.ts in the project ...

Tips for accessing various JSON objects from a JSON document

My task involves extracting specific information from a JSON file using AJAX and jQuery. The structure of my JSON data is as follows: "Footwear": { "Adidas": [ { "id" : 0, &q ...

Steps to Activate a Hyperlink for Opening a Modal Dialogue Box and Allowing it to Open in a New Tab Simultaneously

I am currently working on a website project. Within the website, there is a hyperlink labeled "View Page". The intention is for this link to open the linked page in a modal dialog upon being clicked. Below is the code snippet that I have used to achieve t ...

Assess html code for Strings that include <% %> tags along with embedded scripts

Having a small issue with my code where I am receiving an HTML response from a web service as a java String. I need to display this String as HTML on my webpage, but the problem is that there are some script tags in the form of <% ... %> which are sh ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

Problem: Repeated attempts to open the popup are unsuccessful

Developed a leaflet map featuring markers that open popups when clicked. Also integrated a search bar for marker searchability. However, encountering an issue where each popup can only be opened once and on selecting a marker name, the zoom functionality w ...