javascript - 如何使用 Node.js 将图像路径保存在数据库中?

标签 javascript node.js express body-parser

我正在使用node.js和express开发一个网页。我开发了一个表单,用户可以在其中填写详细信息并上传图像。图像文件应存储在目录中,而路径存储在数据库中。

我正在使用 Node.js 和 mongodb 数据库。图像已成功存储在预期目录中,但路径并未存储在数据库中,而是存储在路径中,我找到了将路径存储在数据库中的代码(/posts/${image.name} 对于每个上传的文件.请问我该如何实现这一目标?

{

//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}}')">

}

最佳答案

使用${}时需要使用反引号,否则字符串将按字面解释:

更改此:

    image: '/posts/${image.name}'

对此:

    image: `/posts/${image.name}`

关于javascript - 如何使用 Node.js 将图像路径保存在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750679/

相关文章:

javascript - 两次格式之间的差异 (hh : mm: ss)

node.js - 如何在没有整个模块的情况下将类型导入 Typescript?

templates - NodeJS + Express + Handlebars - 找不到 View "index.html"

node.js - 错误 : Invalid version: "1.0" in node. js package.json 文件

node.js - 类型错误 [ERR_UNKNOWN_FILE_EXTENSION] :

javascript - 尽管有几种方法,但无法让 clearInterval 工作

javascript - 拼接 forEach 循环无法正常工作

javascript - Nuxt 打开链接到模态

javascript - body 关闭按钮

node.js - 如何使用 ExpressJS 4 上传文件?