【问题标题】:Trying to return a string value from a function and save it to mongoDB doesn't work尝试从函数返回字符串值并将其保存到 mongoDB 不起作用
【发布时间】:2021-02-15 21:34:29
【问题描述】:

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

THE CODE HAS BEEN REMOVED DUE TO PRIVACY CONCERNS

【问题讨论】:

标签: javascript node.js express mongoose multer


【解决方案1】:

这不是错误。这是一个特点。 JavaScript IO 是异步的。最好的办法是让url 返回一个承诺,这样你就可以利用async/awaitMinIOClient 方法在没有回调传递时返回一个承诺,所以使用它。

// 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
    });
});

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2013-07-26
    • 1970-01-01
    • 2011-02-07
    相关资源
    最近更新 更多