Hi every one please can someone help me to update user that receive image and updated it then render the user with the image to frontend.i get stuck I search by google but I didn't find what I search for,there's my code :
this is the userModel:
import mongoose from "mongoose";
const userSchema = new mongoose.Schema({
name: {type: String, required: true},
fname: {type: String, required: true},
phone: {type: String, required: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: false},
image: {type: {name: String, img: {contentType: String, data: Buffer}}, required: false},
isAdmin: {type: Boolean, default: false, required: true},
}, {
timeStamps: true
});
const User = mongoose.model("User", userSchema);
export defau
userRouter.post("/upload/:id", async(req, res)=> {
upload.single("productImage")
const updatedUser = User.findByIdAndUpdate(req.params.id,{$set: {image: {name: req.files.productImage.name, img: {contentType: req.files.productImage.mimetype, data: fs.createReadStream(path.join(__dirname, '../../frontend/public/images'))}}}
})
res.send("ok");
console.log(updatedUser)
})
You have to add option {new: true}, so that the document returned has the last updated data, and also send the http response in the callback of the update operation
userRouter.post('/upload/:id', async (req, res) => {
upload.single('productImage');
const updatedUser = User.findByIdAndUpdate(
req.params.id,
{
$set: {
image: {
name: req.files.productImage.name,
img: {
contentType: req.files.productImage.mimetype,
data: fs.createReadStream(
path.join(__dirname, '../../../frontend/public/images')
),
},
},
},
},
{ new: true },
(err, doc) => {
if (err) return res.send(err);
res.send(doc);
}
);
});