尝试 return 来自函数的字符串值并将其保存到 mongoDB 不起作用
Trying to return a string value from a function and save it to mongoDB doesn't work
我很沮丧。从昨天开始,我一直在尝试修复这个讨厌的错误,但没有任何进展。我想知道我做错了什么。
这就是我想要做的。
在用户提交 enctype 为 "multipart/form-data"
的表单后,我想抓取他上传的图像,将其放入我的 MinIO 数据库(非常类似于 AWS S3),然后生成一个 link 将成为用户的个人资料 link。 link 正确生成,但我找不到将其保存到 Account.pictureUrl
值的方法。非常感谢您的帮助。谢谢!
THE CODE HAS BEEN REMOVED DUE TO PRIVACY CONCERNS
这不是错误。这是一个特点。 JavaScriptIO是异步的。您最好的选择是做出 url
return 承诺,这样您就可以利用 async/await
。 MinIOClient
方法 return 如果没有传递回调,则使用承诺。
// 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
});
});
我很沮丧。从昨天开始,我一直在尝试修复这个讨厌的错误,但没有任何进展。我想知道我做错了什么。
这就是我想要做的。
在用户提交 enctype 为 "multipart/form-data"
的表单后,我想抓取他上传的图像,将其放入我的 MinIO 数据库(非常类似于 AWS S3),然后生成一个 link 将成为用户的个人资料 link。 link 正确生成,但我找不到将其保存到 Account.pictureUrl
值的方法。非常感谢您的帮助。谢谢!
THE CODE HAS BEEN REMOVED DUE TO PRIVACY CONCERNS
这不是错误。这是一个特点。 JavaScriptIO是异步的。您最好的选择是做出 url
return 承诺,这样您就可以利用 async/await
。 MinIOClient
方法 return 如果没有传递回调,则使用承诺。
// 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
});
});