如何从数据库中设置与对象ID相同的文件名?

时间:2022-06-01 21:07:56
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");
});

Here is my app.js file. Now I want to save the image name same as the object id of that specific book data which is generated in database(mongoDB). How can I change the name of file(which is inside storage, filename) in app.post function.

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

2 个解决方案

#1


2  

The second argument to your callback in the filename function is whatever string you want to set it to, so just set it to the UUID you get from the id mongoose creates for you.

文件名函数中回调的第二个参数是你要设置它的任何字符串,所以只需将它设置为你为id mongoose为你创建的UUID。

Example added based on comments.

根据评论添加的示例。

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) 
    }
});

I often solve multistep handlers (e.g. creating a book, uploading a book, responding to the client) by breaking the steps down into individual middleware. For example:

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

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

});

});

#2


1  

Here is an example

这是一个例子

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
      });

#1


2  

The second argument to your callback in the filename function is whatever string you want to set it to, so just set it to the UUID you get from the id mongoose creates for you.

文件名函数中回调的第二个参数是你要设置它的任何字符串,所以只需将它设置为你为id mongoose为你创建的UUID。

Example added based on comments.

根据评论添加的示例。

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) 
    }
});

I often solve multistep handlers (e.g. creating a book, uploading a book, responding to the client) by breaking the steps down into individual middleware. For example:

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

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

});

});

#2


1  

Here is an example

这是一个例子

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
      });