我想查询数据库,如果找到结果则上传文件。目前,情况正好相反。首先上传图像然后搜索并更新数据库。
我需要的值,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'
});
});
//
});
});
答案 0 :(得分:0)
为什么不使用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 更新操作来确保原子操作