【问题标题】:MongoDB/Multer Query DB then upload FileMongoDB/Multer 查询数据库然后上传文件
【发布时间】:2016-11-07 09:35:21
【问题描述】:

我想查询一个数据库,如果找到结果上传一个文件。目前情况正好相反。首先上传图片,然后搜索和更新数据库。

我需要的值 cid(req.body.cid) 只能在调用 upload() 后才能访问,所以这有点复杂,这是我当前的工作代码:

var multer = require('multer');
var upload = multer({
    dest: './public/images/usercontent',
    limits: {
        files: 1,
        fields: 1,
        fileSize: 10000
    },
    fileFilter: function fileFilter(req, file, cb) {
        if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg') {
            req.multerImageValidation = 'wrong type';
            return cb(null, false);
        }
        return cb(null, true);
    }
}).single('uploads[]');

router.post('/uploadimg', isLoggedIn, function(req, res, next) {
    upload(req, res, function(err) {
        if (err) {
            if (err.code === 'LIMIT_FILE_SIZE') {
                return res.send({
                    statusText: 'fileSize'
                });
            }
            return res.send({
                statusText: 'failed'
            });
        }
        if (req.multerImageValidation) {
            return res.send({
                statusText: 'wrongType'
            });
        }
        Company.findOneAndUpdate({
            ownedBy: req.user.local.username,
            _id: req.body.cid // value that is sent with the image
        }, {
            icon: 'images/usercontent/' + req.file.filename
        }, function(err, result) {
            if (err) {
                return res.send({
                    statusText: 'failed'
                });
            }
            if (!result) {
                return res.send({
                    statusText: 'failed'
                });
            }
            res.send({
                statusText: 'success'
            });
        });
      //
    });
});

【问题讨论】:

    标签: ajax mongodb express multer


    【解决方案1】:

    为什么不使用db查询的成功回调上传图片,然后使用上传图片函数的成功回调用cid更新db记录?在非常高的层次上,这将是:

      query db for record
       //if record found, in success callback
       attempt to upload image
           //if image uploaded successfully and cid generated, in success callback
           update db record
    

    可以使用mongo update操作来保证原子操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2018-07-21
      • 2020-07-16
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多