2016-07-05 1 views
0

데이터베이스를 쿼리하고 결과가 발견되면 파일을 업로드하려고합니다. 지금은 다른 방향입니다. 먼저 이미지가 업로드 된 다음 db가 검색되고 업데이트됩니다.MongoDB/Multer DB를 쿼리 한 다음 파일을 업로드하십시오.

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 (req.body.cid) 만이 내 현재, 작업, 코드, 즉 좀 일을 복잡 있도록()를 호출 업로드 후 액세스 할 수 있습니다 왜 당신은 이미지를 업로드 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 

당신은 원자 작동을 보장하기 위해 몽고 업데이 트를 작업을 사용할 수 있습니다

관련 문제