Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the name of file same as object id from database?

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.

like image 769
JohnReese Avatar asked Mar 28 '17 18:03

JohnReese


2 Answers

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.

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

});

like image 62
Paul Avatar answered Oct 16 '22 21:10

Paul


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
      });
like image 24
Richardson. M Avatar answered Oct 16 '22 21:10

Richardson. M