Search code examples
node.jsmongoosemultercloudinary

show cloudinary uploaded image using mongoose


Am trying to upload an image file to cloudinary, and set the url to be saved in my mongodb for viewing in browser. The image uploads to my cloudinary dashboard but the url is not set in my mongodb.

var express               = require("express"),
    app                   = express(),
    bodyParser            = require("body-parser"),
    mongoose              = require("mongoose"),
    multer                = require("multer"),
    cloudinary            = require("cloudinary"),

var promise = mongoose.connect("mongodb://localhost/bito");
app.use(bodyParser.urlencoded({extended: true}));

*user model here*
var UserSchema = new mongoose.Schema({
    userimage: {type: String, default: "https://i.imgur.com/FtjHOne.jpg"},
    })
 mongoose.model("User", UserSchema )

 **multer setup|config**

var storage = multer.diskStorage({
        filename: function(req, file, callback) {
            callback(null, file.originalname)
        }
    })

var imagefilter = function (req, file, cb) {
    if(!file.originalname.match(/\.(jpg|jpeg|png)$/i)) {
        return cb(new Error('only image files are accepted here'), false);
    }
    cb(null, true);
}

var upload = multer({storage: storage, filterHack: imagefilter});
**cloudinary config**

cloudinary.config({
    cloud_name: 'coder',
    api_key: 'MY api key',
    api_secret: "Secret api key",       
})

app.put("/dashboard/:id/updateUserImg", isLoggedIn, upload.single('userimage'), function(req,res){

    cloudinary.uploader.upload(req.file.path, function(result) {
    *setting the userimage to be the uploaded image url*
            req.body.userimage = result.secure_url;

        User.findByIdAndUpdate(req.params.id, req.body.userimage, function(error, updated){
            if(error){
                console.log("error occured " + error);
                return res.redirect("/dashboard")
            } else {
                // console.log("success");
                res.redirect("/dashboard/" + req.params.id + "/view")
            }
        })
    })
})

where am i really getting things wrong. :) as i await your replies


Solution

  • This is the only mistake I see immediately:

    User.findByIdAndUpdate(req.params.id, req.body.userimage...
    

    is not how you update your user. Try this

    User.findByIdAndUpdate(req.params.id, {userimage: req.body.userimage}...
    

    Also I'm not sure if you can add a key to the request.body like that. You should probably just do:

    User.findByIdAndUpdate(req.params.id, {userimage: result.secure_url}...