Nodejs,MongoDB使用multer上传图像

时间:2019-12-10 08:36:42

标签: node.js mongodb express mongoose multer

我正在创建和更新配置文件路线,我可以创建和更新配置文件详细信息,但无法将图像保存到数据库中。我如何将图片网址保存到数据库中?

个人资料模型,头像用于图片:

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

1 个答案:

答案 0 :(得分:1)

您需要这样设置头像:

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