[英]Trying to return a string value from a function and save it to mongoDB doesn't work
I am so frustrated.我很沮丧。 I have been trying to fix this nasty bug since yesterday but there is no progress.
从昨天开始,我一直在尝试修复这个讨厌的错误,但没有任何进展。 I wonder what am I doing wrong.
我想知道我做错了什么。 This is what I want to do.
这就是我想要做的。 After the user submits the form which has enctype of
"multipart/form-data"
I want to grab the image that he has uploaded, put that into my MinIO database ( really similar to AWS S3 ) and then generate a link that will be the user's profile link.在用户提交具有
"multipart/form-data"
加密类型的表单后,我想抓取他上传的图像,将其放入我的 MinIO 数据库(与 AWS S3 非常相似),然后生成一个链接,该链接将成为用户的个人资料链接。 The link generates properly but I can't find a method to save it to the Account.pictureUrl
value.该链接正确生成,但我找不到将其保存到
Account.pictureUrl
值的方法。 Your help will be highly appreciated.您的帮助将不胜感激。 Thank you!
谢谢!
THE CODE HAS BEEN REMOVED DUE TO PRIVACY CONCERNS
It's not a bug.这不是一个错误。 It's a feature.
这是一个特点。 JavaScript IO is asynchronous.
JavaScript IO 是异步的。 Your best bet is to make
url
return a promise, so you can take advantage of async/await
.最好的办法是让
url
返回一个 promise,这样你就可以利用async/await
。 MinIOClient
methods return a promise f no callback is passed, so use that. MinIOClient
方法返回一个没有回调的承诺,所以使用它。
// If a custom image was selected by the client set the picture URL to Firebase's CDN
const url = async () => {
// If the user has selected a file
if (req.file) {
// Upload user image to the database
await MinIOClient.fPutObject("local", `${req.body.email}.png`, req.file.path, {
"Content-Type": req.file.mimetype
});
// Getting the link for the object
const presignedUrl = await MinIOClient.presignedGetObject("local", `${req.body.email}.png`, 24 * 60 * 60)
return presignedUrl;
}
// If the user didn't select an image return a random image link(string) that will be used to serve default avatars from the server
else {
return avatarLinks[Math.floor(Math.random() * avatarLinks.length)];
}
};
Then modify the controller然后修改控制器
router.post("/", upload.single("avatar"), async (req, res) => {
const pictureUrl = await url();
let Account = new AccountSchema({
// ... other values
pictureUrl
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.