I need to link a image to a user using a file.path in multer, but it just doesent save the photo here is my code:
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})
})
As you can see Im passing the user.photo as the req.file.path, but it doesent really save it it return me the path whe I upload but it doesent save, here is my user model:
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,
},
})
CodePudding user response:
You need to add photo before creating user like
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 ?
})