Hapi.js 后无法将上传的图像保存到数据库

Unable to save uploaded image to database in Hapi.js

我想使用 hapi.js 将上传的照片保存在 mongodb 中。但是我可以将照片上传到上传文件夹中,但我无法将其保存在数据库中。这是代码:

   server.route({
            method: 'POST',
            path: '/upload',
            config: {
                    payload: {
                        output: "stream",
                        parse: true,
                        allow: "multipart/form-data",
                        maxBytes: 2 * 1000 * 1000
                    }
                },

                  handler: async (req, h) => {

                    const response1 = handleFileUpload(req.payload.image);
                    console.log(response1);
                    return response1;

                  }
         });
const handleFileUpload = file => {
    return new Promise((resolve, reject) => {
      const filename = file.hapi.filename
      const data = file._data

      fs.writeFile(`./uploads/${filename}`, data, err => {
        if (err) {
          reject(err)
        }
        resolve({
          message: 'Upload successfully!',
          imageUrl: `${server.info.uri}/uploads/${filename}`
        })
      })
    })
  }

因为它发送响应消息和 imageUrl。我必须将该 imageurl 保存在数据库中,但我不知道如何从 promise return 访问它。我很新的承诺。 这是我的模型架构:

const stuSchema = new Schema({
    image : String,
});

html:

   <form method="post" action="/upload" enctype="multipart/form-data">

            <label for="image">Image Upoahhd</label>
            <input name="image" type="file" required >

            <br><br>
            <input type="submit" value="Login">
        </form>

我不知道如何将 req.payload.image 的值保存到数据库中。我想在 handler 方法上这样做:

const user = new User (imageUrl);
const sav = user.save();
return h.response(sav)

但我想将它们写在解析器函数上,但它接受对象

您需要使用 awaithandleFileUpload 函数从 Promise 对象中获取数据,然后您可以在下面使用 save() 函数在内部创建文档数据库。

handler: async (req, reply) => {
  try {
    const { imageUrl } = await handleFileUpload(req.payload.image);
    const user = new User ({ image: imageUrl });
    const result = user.save();
    return ({ message: 'Saved Successfully' });
  } catch (err) {
    throw err
  }
}

const handleFileUpload = file => {
  return new Promise((resolve, reject) => {
    const filename = file.hapi.filename;
    const data = file._data;

    return fs.writeFile(`./uploads/${filename}`, data, err => {
      if (err) {
        return reject(err)
      }
      return resolve({
        message: "Upload successfully!",
        imageUrl: `${server.info.uri}/uploads/${filename}`
      })
    })
  })
}