I’m working on a blog in React and saving everything in MongoDB. I have an article
array with each article having a title
, content
, author
and imagePath
.
const articleSchema = mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
image: { type: String, required: true },
author: { type: String, ref: "User", required: true },
placement: {
type: String,
enum: ["featured", "card", "stories"],
default: "stories",
},
},
{
timestamps: true,
}
);
Everything is wrapped up inside a form, including the image so when the user hits the submit button it publishes. When the user publishes the article, the image gets saved to firebase.
const [image, setImage] = useState(null);
const imagePath = uploadBytes(imageRef, image).then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
console.log(url);
});
});
<Form.Group className="my-2" controlId="content">
<label>Image</label>
<input
type="file"
placeholder="Image"
onChange={(e) => setImage(e.target.files[0])}
></input>
</Form.Group>
Everything works perfectly fine. The article gets published and the image gets saved to Firebase. When I console.log(imagePath)
I get the correct path. When I try saving that to the submitHandler
I get an undefined object saved inside my MongoDB instead of the actual image path.
try {
const res = await write({
title,
content,
username,
placement,
image: toString(imagePath),
}).unwrap();
navigate("/");
toast.success("Article Added!");
} catch (err) {
toast.error(err?.data?.message || err.error);
}
};
MONGODB
_id: 657d70d8af9322a9df1b72be
title: "rhtrth"
content: "rthrth"
image: "[object Undefined]" // imagePath saved as undefined
author: "Dagger"
placement: "featured"
I’m wondering how exactly can I save the image path of my uploaded image inside my MongoDB so when I use loop through the data inside the SingleArticle
page:
<img src={article.image} alt="" fill className={styles.image} />
… it will display the proper image.