使用mongoose显示cloudinary上传的图像

时间:2018-02-19 00:51:59

标签: node.js mongoose multer cloudinary

尝试将图片文件上传到cloudinary,并将网址设置为保存在我的mongodb中,以便在浏览器中查看。图像上传到我的cloudinary仪表板,但是我的mongodb中没有设置url。

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

我在哪里弄错了。 :)等待你的回复

1 个答案:

答案 0 :(得分:1)

这是我立即看到的唯一错误:

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

不是您更新用户的方式。试试这个

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

此外,我不确定您是否可以在请求中添加密钥。你应该这样做:

User.findByIdAndUpdate(req.params.id, {userimage: result.secure_url}...
相关问题