Length Indeterminate - Pug, Express, and MongoDB

I keep encountering a persistent TypeError message stating that the length is undefined in the following code snippet. This issue is quite frustrating, especially since I've utilized the same code elsewhere in my project without any problems.

users.js

router.get('/', function(req, res) {
MongoClient.connect(url, function(err, db) {
    if (err) {
        console.log('unable to connect');
    } else {

        collection = db.collection('users');
        collection.find({}).toArray(function(err, result) {
            if (err) {
                res.send(err);
            } else if (result.length) {
                res.render('users', {
                    "users": result
                });
            } else {
                res.send('No documents found')
            };
            db.close()
        });
      }
   });
});

users.pug

The error messages pinpoint line 11 (each user, i in users) within the following code

extends layout.pug

block content

h3 #{title}

ul
    li
        a(href="users/add") Add New user
ul
    each user, i in users <--- Error occurs here
        li
            p #{users._id}
        li
            p #{users.name}
        li
            p #{users.email}
        li
            p #{users.username}
        li
            p #{users.password}     

If you have any suggestions or solutions to help me troubleshoot this problem, I would greatly appreciate it. Thank you in advance :)

UPDATE: I have resolved the issue by identifying and removing a duplicate router.get('/') route. If you are facing a similar problem, make sure to double-check for any duplicated routes.

Answer №1

Essentially, this indicates that result is not defined. What occurs when you attempt to log result?

In the past, I have corrected comparable issues by sending data from the server using JSON.stringify() and then parsing the data client-side with JSON.parse(). Would you mind giving this a try, logging result, and sharing your findings? :)

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

Prevent AngularJS from entering endless digest loops by incorporating unpredictable content

One of the main components in my structure is an <img ng-repeat="img in api.images" src="{{ img.url }}"> The api object contains a list of image IDs and needs to make HTTP calls to retrieve the URLs for each image ID from the server. However, these ...

Eslint was unexpectedly unable to detect any errors in the .ts files

After creating a SvelteKit project with npm create svelte@latest, I included some .ts files for a particular library. However, when running eslint ., it fails to detect any errors. The default eslint config generated from Svelte is as follows: .eslintrc. ...

uib-datepicker-popup allowing for changing minimum mode dynamically

Is there a way to dynamically set the minMode of an Angular Bootstrap Datepicker? I managed to achieve this using the following code: <input type="text" ng-model="myDate" uib-datepicker-popup="{{datepickerFormat}}" datepicker-options="{& ...

Raphael's path adorned with arrow-shaped tips

Recently delving into raphael.js, I am attempting to create an arrow head on a raphael path element (or draw an arrow from point A to point B). Here is the raphael path (line) that I have sketched from point A to point B on my canvas. Assuming that the val ...

React Router consistently displaying IndexRoute

This is the main file for my app: import React from 'react'; import { render } from 'react-dom'; import { browserHistory, Router, Route, IndexRoute } from 'react-router'; // Components import Main from './components/cor ...

By-passing Mistakes in Iteration in JavaScript

I have been working on using Google's Feed API to fetch images from a feed within an AngularJS controller. It successfully retrieves three images, but encounters an issue when it reaches a Twitter URL, causing the script to break. I would like it to s ...

Creating a Dynamic Input Field List with AngularJS: Learn how to set up a model to store an array for multiple input fields in your

Hey all you AngularJS experts, I have a thought-provoking question for you. I want to generate a dynamic list of form input fields based on a SELECT dropdown. Let's say we have different categories, each with its own unique set of specifications. To c ...

Ensure that the Bootstrap form validation checks for both an empty field and a valid URL

I'm currently working on validating a form field in Bootstrap 4.4. The goal is to not only check if the field is filled out, but also to ensure that it contains a valid URL. This URL can be an internal link, a hostname, or an IP address. However, it m ...

I have developed a website that can calculate the factorial of any given number. The next step is to design a function that will display the step-by-step mathematical process

Could use a hand with this one. The function below is empty and I'm a bit stuck on what to do next. Right now, the webpage displays the factorized number, but I want to show the mathematical equation before it, like so: User inputs: 3 Site outputs: " ...

What is the best way to consolidate all app dependencies into a single package?

Recently, I came across Cory House's ingenious solution for package management in Node.js during his informative presentation. In their project portfolio, House's team maintains a package called Fusion, which serves as a central repository for a ...

Is it feasible to invoke the next() function to pass an error within an Immediately Invoked Function Expression (IIFE) in Node.js / Express and move on to

Query: Can Express be configured to handle errors originating from an IIFE and proceed to the error handling middleware? Context: An IIFE serves as an async wrapper for wrapping await statements. The challenge is encountering difficulties in propagating ...

Using the value from the Vuex state to set the initial value for a different parameter

I am facing an issue with utilizing an array of objects in my Vuex state to set a default value for another parameter, specifically for mainAccount: For instance: const store = new Vuex.Store({ state: { AccountNums: [ { label: 'M ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Utilizing a self-invoking function to incorporate JavaScript

In my role, I am responsible for managing a Content Management System (CMS) used by developers to create content that involves JavaScript. In the past, we placed the content in an iFrame for containment purposes; now, it operates as a single-page client-si ...

Filtering JSON data with JavaScript

Looking to group data in AngularJS using UnderscoreJS. Here is the JSON data: data = [ { "Building*": "Building A", "Wing*": "Wing C", "Floor*": "Floor 3", "Room Name*": "Room 3", "Room Type*": ...

Retrieve information about a parent's data related to child events in Vue.js

I'm working with two components nested inside each other. The parent component has a click event that needs to modify the data value of the child component. <template> <div> ..... ..... <my-component :op ...

Using JSON within a GraphQL type definition in a Node.js environment

Utilizing Node.js, I am making requests to a report API that returns JSON responses. The API accepts different IDs as parameters, resulting in varying responses. For instance: https://report.domain.io/report/1 https://report.domain.io/report/2 Each r ...

Replace the hyphen with a comma using JavaScript

Looking for a way to modify a string like this: "PALS español K- add-on" by replacing the - with ,. The desired output should be: "PALS español K, add-on" Is there a JavaScript solution to achieve this task? ...

Adding a character sequence to a parsed JSON object results in a literal string outcome

I have saved some currency information in the state manager of my app and here is how I am accessing it: For example, to retrieve the value of Euro against the dollar, I use the following code: JSON.parse(this.$store.state.clientSide.currencyrates).rates. ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...