繁体   English   中英

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

[英]How do I save Image path in the database using Node.js?

我正在使用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}}')">

}

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

更改此:

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

对此:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM