skip to Main Content

I’m trying to pass a key-value pair from node js to an EJS file.
using Mongoose for data retrieval
It’s not working.

User.find({}).select('name -_id').select('username').then(
        users =>{
            let JSONobject = {};

            for(var i = 0; i < users.length; i++){
                JSONobject = Object.assign(JSONobject, users[i]);
            }
            console.log(JSON.stringify(JSONobject));
            res.render("ToDo.ejs",{UserLIst: JSONobject.username});
        }
      )

above is the code that I used

getting something like this:

console pic

I was expecting something like this

[
  { username: '[email protected]',
    username: '[email protected]',
    username: '[email protected]' }
]

2

Answers


  1. The JSON structure you’ve provided has a syntax issue because it uses the same key multiple times. If you want to represent a list of users with unique usernames, you should use an array of objects.

    [
      { "username": "[email protected]" },
      { "username": "[email protected]" },
      { "username": "[email protected]" }
    ]
    

    Here is version with array:

    User.find({}).select('name -_id').select('username').then(
            users =>{
                let usernames = users.map(element)=> element.username);
                res.render("ToDo.ejs",{UserLIst: usernames});
            }
          )
    
    Login or Signup to reply.
  2. It seems like the issue lies in how you’re constructing the JSONobject. You’re overwriting the username key in each iteration of the loop, which results in the final object having multiple username keys with different values, and when you pass it to the EJS file, it only takes the last value.

    To fix this, you can create an array of usernames and pass it to the EJS file, try this:

    User.find({}).select('name username -_id').then(users => {
        const usernames = users.map(user => user.username);
        console.log(usernames); // checking the usernames here
    
        res.render("ToDo.ejs", { UserList: usernames });
    }).catch(err => {
        // Handle error here
        console.error(err);
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search