简体   繁体   中英

update image from nodejs using multer

i have upload image using multer in nodejs and image is stored in database also displayed in website also but while updating title and description are updated but image is not updated how can i update the image?

this is my controller

router.post('/',upload.single('image'),(req,res)=>{
    if(req.body._id == ''){
        insertRecord(req,res)
    }
    else {
        updateRecord(req,res);
    }
    
})

function updateRecord(req,res){
    
    Blog.findOneAndUpdate({ _id: req.body._id},req.body, { new: true},(err,doc)=>{
        if(!err){res.redirect('blog/list')}
        else{
            if(err.name == 'Validation Error'){
                handleValidationError(err,req.body)
                res.render("blog/addOrEdit",{
                    viewTitle:"insert about file",
                    blog: req.body
                })
            }else{
                console.log("error during record update: " +err)
            }
            
        }
    })

}
function insertRecord(req,res){
    var blog = new Blog()
    blog.title = req.body.title
    blog.description = req.body.description
    blog.img = req.file.filename
    blog.save((err,doc) =>{
        if(!err){
            res.redirect('blog/list')
        }
        else{
            if(err.name == 'Validation Error'){
            handleValidationError(err,req.body)
            res.render("blog/addOrEdit",{
                viewTitle:"insert about file",
                blog: req.body
            })
            }
            else{
            console.log('Error duing record insertion: '+err)
            }
        }
    })
}

You are giving findOneAndUpdate function req.body as data but it does not include image filename since filename is at req.file.filename .

You can give {...req.body, img:req.file.filename} to it instead of req.body with spread operator. It takes all properties from req.body and adds img property with value req.file.filename . I used "img" property since you set blog.img when inserting a blog.

Alternatively, you can create a new object and set img property:

const updateData = Object.assign({},req.body); // Copy req.body in order not to change it
updateData.img = req.file.filename
Blog.findOneAndUpdate({ _id: req.body._id},updateData...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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