【问题标题】:show cloudinary uploaded image using mongoose使用 mongoose 显示 cloudinary 上传的图像
【发布时间】:2018-07-29 05:19:55
【问题描述】:

我正在尝试将图像文件上传到 cloudinary,并将 url 设置为保存在我的 mongodb 中以便在浏览器中查看。图片上传到我的云端仪表板,但我的 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")
            }
        })
    })
})

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

【问题讨论】:

    标签: node.js mongoose multer cloudinary


    【解决方案1】:

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

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

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

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

    我也不确定您是否可以像这样向 request.body 添加密钥。你可能应该这样做:

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

    【讨论】:

    • 感谢您,一切正常。我用 {userimage: req.body.userimage}。感谢您的回复,快乐编码@RobertMoskal
    猜你喜欢
    • 2014-11-29
    • 2015-12-19
    • 2020-04-07
    • 1970-01-01
    • 2021-03-20
    • 2020-03-02
    • 2020-12-10
    • 2019-04-17
    • 2017-06-03
    相关资源
    最近更新 更多