Nodejs, MongoDB 使用 multer 上传图片

Nodejs, MongoDB upload image with multer

我正在创建和更新个人资料路线,我能够创建和更新个人资料详细信息,但我无法将图像保存到我的数据库中。我要如何将图像 url 保存到我的数据库?

个人资料模型,头像为图像:

const ProfileSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  location: {
    type: String
  },
  occupation: { type: String },
  bio: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  },
  avatar: { type: String }
});

多重设置:

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "./uploads/");
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname);
  }
});
const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/jpeg" ||
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 2
  },
  fileFilter: fileFilter
});

配置文件路由,我如何将文件路径存储到我的数据库

router.post("/", auth, upload.single("avatar"), async (req, res) => {
  console.log(req.file);

  const { location, occupation, bio } = req.body;
  const { avatar } = req.file.path;
  //Build profile object
  const profileFields = {};
  if (location) profileFields.location = location;
  if (occupation) profileFields.occupation = occupation;
  if (bio) profileFields.bio = bio;

  try {
    // Using upsert option (creates new doc if no match is found):
    let profile = await Profile.findOneAndUpdate(
      { user: req.user.id },

      { $set: profileFields },
      { new: true, upsert: true }
    );
    res.json(profile);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});

您需要这样设置您的头像:

  if (req.file.path) profileFields.avatar = req.file.path;

所以所有代码必须是这样的:

router.post("/", auth, upload.single("avatar"), async (req, res) => {
  console.log(req.file.path);

  const { location, occupation, bio } = req.body;
  //const { avatar } = req.file.path;
  //Build profile object
  const profileFields = {};
  if (location) profileFields.location = location;
  if (occupation) profileFields.occupation = occupation;
  if (bio) profileFields.bio = bio;
  if (req.file.path) profileFields.avatar = req.file.path;

  try {
    // Using upsert option (creates new doc if no match is found):
    let profile = await Profile.findOneAndUpdate(
      { user: req.user.id },

      { $set: profileFields },
      { new: true, upsert: true }
    );
    res.json(profile);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});