我創建了下面的代碼,但是我似乎無法弄清楚如何更新圖片,如果findOneAndUpdate
找到結果並且看起來好像result.save
在put_form_url之前被執行。我如何實現這樣一個功能,如果它存在它將更新所有屬性並將新圖像上傳到s3,否則它將創建一個帶有s3上傳的新對象。if exists update else插入圖片上傳
router.post('/:id/:name/:birth/:country/:image', function(req, res, next) {
var params = req.params;
var accessHeader = req.headers;
process.env.AWS_ACCESS_KEY_ID=''
process.env.AWS_SECRET_ACCESS_KEY=''
AWS.config.region = 'eu-west-1';
var s3 = new AWS.S3();
User.findOneAndUpdate({"_id": params.id}, {$set:{"name": params.name, "birthday": params.birth, "country": params.country}}, {new: true}, function(error, result) {
if (!error) {
// If the document doesn't exist
if (!result) {
// Create it
put_from_url(params.image, new Date().toString, function(err, res) {
result = new User({
_id: params.id,
name: params.name,
birthday: new Date(params.birth),
country: params.country,
image: "url" + params.id
});
});
}
// Save the document
result.save(function(error) {
if (!error) {
res.json({ message: 'User created!' });
} else {
res.send(err);
}
});
}
});
});
上傳功能
function put_from_url(url, key, callback) {
request({
url: url,
encoding: null
}, function(err, res, body) {
if (err)
return callback(err, res);
uploader.putObject({
Bucket: "",
Key: "/" + key,
ContentType: res.headers['content-type'],
ContentLength: res.headers['content-length'],
Body: body // buffer
}, callback);
})
}