Reputation: 45
I am using Node/Express and mongoose to build an app. I am creating 'Photo' objects in my database (schema shown below) which is basically just an image object.
var PhotoSchema = new mongoose.Schema({
image: { data: Buffer, contentType: String },
name: String
});
I can successfully upload and create photo objects and now I am creating an /images view where I want to extract every photo object and render it as an image. I am using ejs for my views. After doing some googling I hav come up with the following for my images.ejs file :
<% photos.forEach(function(photo){ %>
<img src="/img/<%=photo._id%>" >
<% }) %>
When I load /images it says "photos is not defined".
This is the first time I have tried to directly extract mongoose objects onto an ejs page - is there something else I need to do/include so that my function understands I am referring to the photo objects in my database?
I also have the following routes:
router.get('/img', function (req, res, next) {
try {
Photo.findOne({}, function (err, doc) {
if (err)
res.send(err);
if (doc) {
res.contentType(doc.image.contentType);
res.send(doc.image.data);
}
});
}
catch (e) {
res.send(e);
}
});
router.get('/img/:id', function (req, res) {
try {
Photo.findOne({ _id: req.params.id }, function (err, doc) {
if (err)
res.send(err);
res.setHeader('Cache-Control', 'public, max-age=3000000');
res.contentType(doc.image.contentType);
res.send(doc.image.data);
});
}
catch (e) {
res.send(e);
}
});
router.get('/images', function (req, res) {
try {
Photo.find({}, function (err, doc) {
if (err)
res.send(err);
res.render('images', { images: doc });
});
}
catch (e) {
res.send(e);
}
});
Thank you!
Upvotes: 1
Views: 1352
Reputation: 106698
Your view variable is images
(res.render('images', { images: doc });
), not photos
. Rename one or the other and it should work.
Upvotes: 1