multer和保存mongodb模型时出现问题

时间:2019-06-12 16:59:45

标签: javascript node.js mongodb multer

我正在使用multer将文件上传到我的后端。这是路线:

// @route  POST api/users/resume
// @desc   Upload user resume
// @access Private
router.post("/resume", auth, async (req, res) => {
  try {
    let resumeBackupName = null;

    let resumeMatrix = {
      "application/vnd.ms-excel": "xls",
      "application/msword": "doc",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
        "docx",
      "application/pdf": "pdf"
    };

    let user = await User.findById({ _id: req.user.id.toString() });

    if (
      user.resume &&
      user.resume.extension &&
      user.resume.extension.length > 0
    ) {
      resumeBackupName =
        req.user.id.toString() +
        "-backup-" +
        user.resume.extension.length.toString() +
        "." +
        user.resume.extension[user.resume.extension.length - 1];

      user.resume.backup.push(resumeBackupName);
    }

    let date = new Date();
    let resumeMimeType = null;
    let resumeExtension = null;

    const storage = multer.diskStorage({
      destination: (req, file, cb) => {
        cb(null, "public");
      },
      filename: (req, file, cb) => {
        cb(
          null,
          req.user.id.toString() +
            "-" +
            date.getTime() +
            "-" +
            file.originalname
        );
      }
    });

    const upload = multer({ storage: storage }).single("file");

    upload(req, res, err => {
      resumeMimeType = req.file.mimetype;
      resumeExtension = resumeMatrix[resumeMimeType];

      user.resume.mimeType = resumeMimeType;
      user.resume.extension.push(resumeExtension);

      if (err instanceof multer.MulterError) {
        return res.status(500).json(err);
      } else if (err) {
        return res.status(500).json(err);
      }
    });

    await user.save();

    return res.json({ msg: "Success!" });
  } catch (err) {
    console.log(err);
    res.status(500).send("Server error");
  }
});

问题出在上传功能之内。在useruser.resume.mimeType = resumeMimeType;行之后的控制台日志记录user.resume.extension.push(resumeExtension);会正确显示这些值,但是当命中await user.save()时,它不会保存任何内容。是范围问题吗?我收到variables declared but never usedlet resumeMimeType = null;的警告let resumeExtension = null;,但是它们在上载功能中使用。不知道我在做什么错。

0 个答案:

没有答案