2016-07-05 67 views
0

我想查询数据库,如果发现结果上传文件。目前情况正好相反。首先上传图像,然后搜索并更新数据库。MongoDB/Multer查询数据库然后上传文件

的值,我需要,CID(req.body.cid),只能上传之后访问()被调用,这样还挺复杂的事情,这是我当前的工作,代码:

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' 
      }); 
     }); 
     // 
    }); 
}); 

回答

0

为什么不使用数据库查询的成功回调来上传图像,然后使用上传图像函数的成功回调来用cid更新数据库记录?在一个非常高的水平,这将是:

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 

可以使用蒙戈更新操作,以确保原子操作