[英]Nodejs, MongoDB upload image with multer
I'm doing create & update profile route, i'm able to create & update the profile details, but i not able to save the image into my database.我正在创建和更新配置文件路由,我可以创建和更新配置文件详细信息,但我无法将图像保存到我的数据库中。 How am i going to save the image url to my database?
我如何将图像 url 保存到我的数据库?
Profile Model, avatar is for the image:个人资料模型,头像为图片:
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 }
});
Multer setup:多路设置:
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
});
Profile route, how do i store the file path to my database配置文件路径,我如何将文件路径存储到我的数据库
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");
}
});
You need to set your avatar like this:你需要像这样设置你的头像:
if (req.file.path) profileFields.avatar = req.file.path;
So all code must be like this:所以所有的代码必须是这样的:
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");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.