Reputation: 1013
So I Have some data in my Mongo Database, which I.find()
by express and send it to my EJS view. pretty simple. But the problem is when I try to read it using <pre><%=%></pre>
i get undefined. Here's the entire code:
The Data Array containing Object in MongoDB:
[{
_id: 6069820f402d01120cda8cff,
imageName: 'Dining Plate',
imagePath: './public/assets/img/6.jpg',
description: 'Wallpapers',
__v: 0
}]
Express Code where I get it and send it to EJS:
app.get('/wallpapers/:id', ((req, res) => {
const urlID = req.params.id;
Thing.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
var fres = result.filter(d => d._id == urlID);
res.render('wallpaper-page',{fres});
}
});
})
)
and the EJS:
<pre><%= fres.description%> %> </pre>
And Now the BIG CONFUSION: when I replace fres.description
with fres._id
, It works perfectly fine. but that's it, it doesn't wanna print any other key values. I've been searching far and wide for almost a day now. But nothing helps. this is annoying me now.
PS: console.log(fres.description)
is undefined
and console.log(fres._id)
works fine.
Why? How do I fix this? please tell me if you need any other code.
Upvotes: 0
Views: 411
Reputation: 5411
Besides the problem with the filter method returns an array, I think you have another problem accessing data from Mongoose response.
This problem is discussed here: Mongoose return data inside _doc object. You can check out my answer with a test code to demonstrate some methods to access data from Mongoose response.
Upvotes: 1
Reputation: 8158
Array.filter
returns an array. So, var fres = result.filter(d => d._id == urlID);
the variable fres
is an array with an object in it.
And if you need only the object in your EJS template, you need to pass just that.
res.render('wallpaper-page',{fres: fres[0]});
Now you can access the description
key directly. But I don't understand how fres._id
works, it should also be undefined
.
Upvotes: 0