Photo Upload and display using Express, MongoDB and pug js. Images aren't been displayed.
I've successfully uploaded the photos and saved them to mongodb; but I haven't been able to properly display them on the browser. The image output instead looks as though there's a bad internet connection or something. I've been struggling with this for a week now; any help or effort is greatly appreciated. Pls look through my code.
const express = require('express');
const multer = require('multer');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const Test = require('./models/models');
const app = new express();
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost:27017/trymult');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
app.use(bodyParser.json());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.get('/', function(req, res){
res.render('index');
});
app.post('/', multer({ dest: './public/'}).array('photos', 5), function(req,res){
//console.log(req.body); //form fields
const title = req.body.title;
const photos = req.files;
let newTest = new Test({
title: title,
photos: photos
});
newTest.save(function(err) {
if(err){
res.send(err);
}
res.redirect('/');
});
});
app.get('/tests', function(req, res) {
Test.find({}, function(err, tests) {
if(err) {
res.send(err);
}
let model = {
tests: tests,
};
res.render('tests', model);
});
});
/*app.get('/tests', function(req, res) {
res.render('tests');
});*/
const port = 3000;
app.listen( port, function(){ console.log('listening on port '+port); } );
Below are my models and photo schema
//Test model
const mongoose = require('mongoose');
const photoSchema = require('./photo');
const TestSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
photos: [photoSchema]
});
const Test = mongoose.model('Test', TestSchema);
module.exports = Test;
my Photo schema
//photo schema
const mongoose = require('mongoose');
const PhotoSchema = new mongoose.Schema({
originalname: {
type: String
}
});
//const Photo = mongoose.model('Photo', PhotoSchema);
module.exports = PhotoSchema;
I'm also including my pug code
html
head
title
body
block content
if tests
each test, i in tests
h1=test.title
img(src='/public/#{test.photos[0]}')
p=test.photos[0].originalname
p=test.photos.length
a(href='/photos') go to photos
via Emmanuel Wayne
No comments:
Post a Comment