Reputation: 25
I am developing a web page with node.js and express. I developed a form where users can fill their details and upload their image. The image file is expected to be stored inside a directory while the path is stored in the database.
I am using Node.js with mongodb database. The image is successfully stored in the expected directory but the path is not stored inside the database instead of the path, I found the code to store the path inside the database (/posts/${image.name} for every of the file uploaded. please how do I achieve this?
{
//Index.js
const path = require('path');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Post = require('./database/models/Post');
const fileUpload = require("express-fileupload");
const app = new express();
mongoose.connect('mongodb://localhost/node-js-test-blog', { useNewUrlParser: true })
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload());
//the route responsible for storing the image in posts directory and the path in the database
app.post('/posts/store', (req, res) => {
const { image } = req.files
image.mv(path.resolve(__dirname, 'public/posts', image.name), (error) => {
Post.create({
...req.body,
image: '/posts/${image.name}'//this code is what I get in the database instead of the path
}, (error, post) => {
res.redirect("/");
});
})
});
app.listen(4000, () => {
console.log("application listening on port 4000")
})
}
//model
const mongoose = require('mongoose');
//collections represents entities in the application e.g users, posts, etc
//schema represents how to structure in the collections
const PostSchema = new mongoose.Schema({
description: String,
title: String,
content: String,
username: String,
image: String,
createdAt: {
type: Date,
default: new Date()
}
});
//the model itself is what will communicate with the database
const Post = mongoose.model('Post', PostSchema);
module.exports = Post;
}
//the code to display the (image) view from the database using node.js directive
<style="background-image: url('{{post.image}}')">
}
Upvotes: 1
Views: 4871
Reputation: 16032
You need to use backticks when using ${}
, otherwise the string is interpreted literally:
Change this:
image: '/posts/${image.name}'
To this:
image: `/posts/${image.name}`
Upvotes: 3