javascript - 如何将文件名设置为与数据库中的对象 ID 相同?

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 函数中更改文件名(在存储中,文件名)。

最佳答案

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

根据评论添加的示例。

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

});

https://stackoverflow.com/questions/43076998/

相关文章:

mongodb - 如何使用 electron 和 pouchdb 创建一个持久的离线数据库

mongodb - 语法错误 : missing ) after argument list @(s

python - 大内存 Python 后台作业

javascript - 如何在 Node 议程中以编程方式定义多个具有相同名称的作业

mongodb - max_df 对应的文档比 Ridge 分类器中的 min_df 错误

java - 从 JAVA 应用程序使用 SSL 连接到 MongoDb

mongodb - 为什么 mongo dot notation 会替换整个子文档?

node.js - Mongoose(或类似的 ODM)内存记录注册表?

node.js - mongoose.connection.collections.collecti

node.js - 如何在 Mongoose 中定义排序函数