【问题标题】:How do I save Image path in the database using Node.js?如何使用 Node.js 在数据库中保存图像路径?
【发布时间】:2019-09-02 01:53:35
【问题描述】:

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

我正在使用带有 mongodb 数据库的 Node.js。图像已成功存储在预期的目录中,但路径未存储在数据库中而不是路径中,我找到了将路径存储在数据库中的代码(/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}}')">

}

【问题讨论】:

  • 在 req.body 上做一个console.log,看看它的 image 数据是什么,然后相应地更改代码中的字段名称
  • ${image.name} 仅适用于反引号/模板文字

标签: javascript node.js express body-parser


【解决方案1】:

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

改变这个:

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

到这里:

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

【讨论】:

  • 非常感谢这个解决方案完全解决了问题
猜你喜欢
  • 1970-01-01
  • 2015-07-14
  • 2012-01-27
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 2019-04-02
  • 2015-10-12
  • 2021-02-07
相关资源
最近更新 更多