首页 > 解决方案 > 尝试从函数返回字符串值并将其保存到 mongoDB 不起作用

问题描述

我很沮丧。从昨天开始,我一直在尝试修复这个讨厌的错误,但没有任何进展。我想知道我做错了什么。这就是我想做的。在用户提交具有 enctype 的表单后,"multipart/form-data"我想抓取他上传的图像,将其放入我的 MinIO 数据库(非常类似于 AWS S3),然后生成一个链接,该链接将是用户的个人资料链接。该链接生成正确,但我找不到将其保存到该Account.pictureUrl值的方法。您的帮助将不胜感激。谢谢!

THE CODE HAS BEEN REMOVED DUE TO PRIVACY CONCERNS

标签: javascriptnode.jsexpressmongoosemulter

解决方案


这不是一个错误。这是一个特点。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
    });
});

推荐阅读