我需要使用文件将图像链接到用户。路径在multer中,但它不保存照片下面是我的代码:
router.post('/register',upload.single('profilepic'), async (req, res) =>{
const {email} = req.body
try{
if(req.file != undefined){
const post = await Post.create({
name: req.file.originalname,
size: req.file.size,
key: req.file.filename,
photo: req.file.path,
url: ''
})
console.log(req.file)
//console.log(req.body)
if (await User.findOne({ email }))
return res.status(400).send({error: 'User already exists'})
const user = await User.create(req.body)
user.password = undefined
user.photo = req.file.path
return res.send({
user,
token: generateToken({ id: user.id})
})
你可以看到我传递用户。照片作为req.file。路径,但它不会保存它在我上传时返回路径,但它不会保存,这是我的用户模型:
const UserScheme = new mongoose.Schema({
title:{
type: String,
required: true,
},
description:{
type: String,
required: false
},
email:{
type: String,
unique :true,
required: true,
lowercase: true
},
photo:{
type:String,
required: false,
select:true
},
password:{
type :String,
required: true,
select:false
},
passwordResetToken:{
type: String,
select: false
},
passwordResetExpires:{
type: Date,
select: false
},
createdAt:{
type: Date,
default: Date.now,
},
})
在创建像
这样的用户之前需要添加照片req.body.photo = req.file.path;
const user = await User.create(req.body);
user.password = undefined
return res.send({
user,
token: generateToken({ id: user.id}) // user.id or user._id ?
})