Retrieve the IDs of all currently logged in users using express.js

Currently, I am working on a project and need to extract a list of user ids of all currently logged in users. I came across a relevant question on StackOverflow at this link. However, I am facing difficulties in accessing the object properties as intended.

My current code snippet looks like this:

let sessions = req.sessionStore.sessions
console.log(JSON.stringify(sessions))

Upon running this code, the console outputs a JSON object containing information about the logged-in users.

From the output, it's clear that there are two logged-in users. My objective now is to loop through the object and print out the user ids located within the passport property to the console.

I attempted the following code:

for (sesh in sessions) {
    console.log(sessions[sesh].passport.user.id)
}

However, this code snippet returns undefined. I also tried using sessions.forEach(), but unfortunately, that didn't work either.

Can anyone point out what I am doing wrong? Do I need to parse the JSON object before accessing the user ids?

Answer №1

The information is saved in a JSON format, which requires parsing to access specific properties:

for (session in sessions) {
  console.log(JSON.parse(sessions[session]).passport.user.id)
}

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

Instantly display selected image

I have encountered some challenges with my previous question on Stack Overflow as I couldn't find a suitable solution. Therefore, I decided to explore an alternative method for uploading images. My current goal is to upload an image immediately after ...

Calculating the 2D transformation matrix between two triangles using JavaScript

Seeking to determine the 2D transformation matrix for converting one triangle into another. The coordinates of both triangles' points are known. Although I typically utilize Paper.js for manipulating matrices, this particular scenario is outside i ...

Error in AJAX transmission

I am encountering an unusual issue with the jQuery ajax function in my script. The problem is specific to my friend's computer, as I am not experiencing any difficulties on my own computer. While attempting to utilize the error function property to ...

What could possibly be causing this element to shift side to side (in IE only) during the CSS animation?

UPDATE: Issue occurring on Internet Explorer 10, Windows 7 When using the transform property to adjust the horizontal position of an element during animation, the vertical value is updated as well. However, despite setting the horizontal value to the same ...

The form data does not contain any request body information upon submission

When I try to update using raw JSON, it works perfectly fine. However, when I use form data, the request body appears as an empty object and the update does not happen. Can anyone explain why this is occurring? Below is the snippet of my update code: exp ...

Tips for sending a JavaScript object to a Java Servlet

I'm facing a challenge with passing a JavaScript object to a Java Servlet. I've experimented with a few approaches, but nothing has worked so far. Below is the code snippet I've been working on: $.ajax({ url: 'TestUrl', d ...

How can you determine whether the CSS of a <div> is defined in a class or an id using JavaScript/jQuery?

Hey there, I'm currently working on dynamically changing the CSS of a website. Let's say we have a div like this: <div id="fooid" class="fooclass" ></div> The div has a class "fooclass" and an ID "fooid", and we're getting its ...

How to modify an element in an array using NodeJS and MongoDB

**I need assistance updating the "paymentStatus" field within either the "ballpool" or "valorant" game arrays. I am working with NodeJS and would appreciate guidance on how to update the payment status by passing in the value of "ballpool" or "valorant" as ...

Steps for submitting a form once all inputs have been verified

$('#f_name, #l_name').change(function(){ if($(this).val().length < 2) { $(this).css('border', '1px solid red'); alert('names must be at least 2 symbols'); check ...

Syntax Error Unearthed: Identifier Surprise Discovered in (Javascript, ASP.NET MVC, CSHTML)

I encountered an error when attempting to remove a dynamically created HTML element by clicking the corresponding remove button. The goal is to invoke the remove method at the end of the script and pass along certain arguments. However, I'm facing iss ...

``I am experiencing issues with the Ajax Loader Gif not functioning properly in both IE

I am brand new to using ajax and attempting to display a loading gif while my page loads. Interestingly, it works perfectly in Firefox, but I cannot get it to show up in Chrome or IE. I have a feeling that I am missing something simple. The code I am using ...

Increasing a variable in MongoDB using Meteor.js based on the value of a variable in a separate document

I am facing an issue similar to this: I am struggling to modify multiple documents simultaneously. click: function() { var power = Meteor.user().power; var mult = Meteor.user().mult; Meteor.users.update({ _id: this.use ...

Clicking the download button will trigger the file to be downloaded every time

Within the documents table, I am iterating through metadata to extract a filename and docid which are then passed to my DocumentDownloadButton component: const DocumentsTableBody = ({ documentMetadata, tableProps }) => { const { Row, Data } = Table ...

Determine the number of objects in a JSON array and compile a new array containing the sum of the

I am working with a JSON array that looks like this: const arrayVal = [{ "DATE": "2020-12-1", "NAME": "JAKE", "TEAM_NO": 2, }, { "DATE": "2020-12-2"`, "NAME" ...

Ways to set a header value before the initial body byte in express.js using hooks or callbacks

Within the global application-level middleware of express.js (4.16.4) and node.js (10.15.1), there is a specific requirement to set a cookie in the response header just before any middleware writes the initial byte to the body. An ideal solution would inv ...

In the event of a 404 error, simply direct the user to the pageNotFound before ultimately guiding them back

I'm developing a website with Node JS and I want to implement a feature where if the user attempts to navigate to a non-existent page, they are redirected to a "Page Not Found" message before being automatically taken back to the home page after a few ...

Automatically populate select boxes with values from a different source using PHP

I'm in the process of setting up automatic population for 2 select boxes on a website. When a user chooses a class, the second select box automatically displays the main specialization of that class. If the user selects Tank (for example), the third ...

Invoking AJAX function post readystatechange

Currently, I am in the process of making an Ajax call to a server and attempting to invoke another function once the response is ready (readystatechanged). As of now, there isn't any serverside code implemented. Surprisingly, Chrome and Firefox encoun ...

Adding Bootstrap component via ajax request

I'm facing an issue with injecting a Bootstrap component using ajax. I usually include a select element like this: <select class="selectpicker" data-width="75%"> Most of the HTML code is generated dynamically through javascript, which you can ...

The process of transferring ViewBag value as a parameter in an AngularJS function

I'm facing an issue where the viewbag value is not being passed as a parameter in ng-init. Can someone guide me on how I can successfully pass the viewbag value as a parameter? angular.js { $scope.detail = function (Id) { ...