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:
I was expecting something like this
[
{ username: '[email protected]',
username: '[email protected]',
username: '[email protected]' }
]
2
Answers
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.
Here is version with array:
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: