javascript - 尝试从函数返回字符串值并将其保存到 mongoDB 不起作用
问题描述
我很沮丧。从昨天开始,我一直在尝试修复这个讨厌的错误,但没有任何进展。我想知道我做错了什么。这就是我想做的。在用户提交具有 enctype 的表单后,"multipart/form-data"
我想抓取他上传的图像,将其放入我的 MinIO 数据库(非常类似于 AWS S3),然后生成一个链接,该链接将是用户的个人资料链接。该链接生成正确,但我找不到将其保存到该Account.pictureUrl
值的方法。您的帮助将不胜感激。谢谢!
THE CODE HAS BEEN REMOVED DUE TO PRIVACY CONCERNS
解决方案
这不是一个错误。这是一个特点。JavaScript IO 是异步的。你最好的选择是做出url
回报的承诺,这样你就可以利用async/await
. 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)];
}
};
然后修改控制器
router.post("/", upload.single("avatar"), async (req, res) => {
const pictureUrl = await url();
let Account = new AccountSchema({
// ... other values
pictureUrl
});
});
推荐阅读
- talend - 使用 tWaitForFile 监视远程共享文件夹上的文件
- python - 是否可以在函数中直接使用 PyObject 引用?
- hadoop - 如何比较 S3 和 hdfs 的性能?
- node.js - TypeError:products.find 不是函数节点 js
- javascript - 如何在不删除最后一个元素的情况下将项目推入数组
- python - 如何加快 Python 中将 QuerySet 对象转换为 JSON 数组的过程
- javascript - 更改基础对象的属性
- c# - 应用程序自行更改 DPI
- javascript - 节点函数执行顺序
- javascript - React Native 和地图