【问题标题】:How can I set the name of file same as object id from database?如何将文件名设置为与数据库中的对象 ID 相同?
【发布时间】:2017-08-21 23:11:38
【问题描述】:
var express = require("express");
var app = express();
var mongoose = require("mongoose"),
    bodyParser = require("body-parser"),
    methodOverride = require("method-override"),
    Book = require("./models/book"),
    multer = require('multer');


var storage = multer.diskStorage({
    destination: function (request, file, callback) {
        callback(null, 'uploads/');
    },
    filename: function (request, file, callback) {
        console.log(file);
        callback(null, file.originalname) 
    }
});
var upload = multer({ storage: storage });

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/books")
app.set("view engine", "ejs")
app.use(express.static(__dirname + "/public"))
app.use(methodOverride("_method"));
app.use(bodyParser.urlencoded({ extended: true }));


app.get("/", function (req, res) {
    res.redirect("/books")
})


//Add new book
app.get("/books/new", function (req, res) {
    res.render("books/new.ejs")
})

//CREATE BOOK logic
app.post("/books", upload.single('photo'), function (req, res, next) {
    var name = req.body.name;
    var price = req.body.price;
    var desc = req.body.desc;
    var newBook = { name: name, price: price, desc: desc }
    // I want to change the name of image same as the id of this database data 
    Book.create(newBook, function (err, newlyCreated) {
        if (err) {
            console.log(err)
        } else {
            res.redirect("/books")
        }
    })

})



//SHOW page
app.get("/books/:id", function (req, res) {
    Book.findById(req.params.id).exec(function (err, foundBook) {
        if (err) {
            console.log(err)
        } else {
            res.render("books/show.ejs", { books: foundBook });
        }
    })
})

app.get("*", function (req, res) {
    res.send("Error 404");
});

app.listen(3000, function () {
    console.log("server started");
});

这是我的 app.js 文件。现在我想保存与在数据库(mongoDB)中生成的特定书籍数据的对象 ID 相同的图像名称。如何在 app.post 函数中更改文件名(在存储中,文件名)。

【问题讨论】:

    标签: javascript node.js mongodb express multer


    【解决方案1】:

    文件名函数中回调的第二个参数是您想要设置的任何字符串,因此只需将其设置为您从 id mongoose 为您创建的 UUID 即可。

    基于 cmets 添加的示例。

    var storage = multer.diskStorage({
        destination: function (request, file, callback) {
            callback(null, 'uploads/');
        },
        filename: function (request, file, callback) {
            if (request.book) {
               // TODO: consider adding file type extension
               return callback(null, request.book.id.toString());
            }
            // fallback to the original name if you don't have a book attached to the request yet. 
            return callback(null, file.originalname) 
        }
    });
    

    我经常通过将步骤分解为单独的中间件来解决多步骤处理程序(例如,创建一本书、上传一本书、响应客户端)。例如:

    var upload = multer({ storage: storage });
    function createBook(req, res, next) {
        var name = req.body.name;
        var price = req.body.price;
        var desc = req.body.desc;
        var newBook = { name: name, price: price, desc: desc }
        // I want to change the name of image same as the id of this database data 
        Book.create(newBook, function (err, newlyCreated) {
            if (err) {
                next(err)
            } else {
                req.book = newlyCreated;
                next();
            }
        })
    }
    
    app.post('/books', createBook, upload.single('photo'), function(req, res) {
      // TODO: possibly return some code if there's no book, or redirect to the individual book page
      res.redirect('/books');
    });
    
    // add error handler for one-stop logging of errors
    app.use(function(err, req, res, next) {
       console.log(err);
       next(err); // or you can redirect to an error page here or something else
    

    });

    【讨论】:

    • 是的,但是 book 的 id 稍后会在 app.post 中生成。如何在生成 id 之前将名称设置为?
    • 数据保存到数据库后,您可以保存或移动或重命名(对象ID为文件名)文件
    • 将新书附加到请求对象,然后如果您的 multer middlware 设置为在之后运行,您的文件名函数将可以访问它
    • @JohnReese 示例已添加。
    【解决方案2】:

    这是一个例子

    var data = { title: "new title" }; 
    var options = { new: true };                     
       MyModel.create (query, data, options, 
         function(err, doc) {
             //here you got id
             console. log(doc._id) 
             // save your file here
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多