I am trying to create a file upload API with some other content as well. For file upload i am using express-file-upload
package . But I don't know how to save its path to MongoDB data base i tried searching but could not able to find any solution. I am new to backend development.
This is my controller file.
Here is my code:
exports.createNewPost = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error = new Error("Validation failed, entered data is incorrect");
error.statusCode = 422;
throw error;
}
if (!req.files) {
const error = new Error("No Image provided");
error.statusCode = 422;
throw error;
}
const { title, content } = req.body;
console.log("reqfile", req.files); <-- Here it does log all the image detail but i don't know how to use them
const imageUrl = req.files.image;
imageUrl.mv("./uploads/" + imageUrl.name);
const post = new Post({
title,
content,
imageUrl,
creator: {
username: "Aditya",
},
});
post
.save()
.then((result) => {
res.status(201).json({
message: "Post created successfully",
post: result,
});
})
.catch((err) => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
};
Here is my modal:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const postSchema = new Schema(
{
title: {
type: String,
required: true,
},
imageUrl: {
type: String,
},
content: {
type: String,
required: true,
},
creator: {
type: Object,
required: true,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Post", postSchema);
question from:https://stackoverflow.com/questions/65540897/how-to-save-image-path-to-mongodb-database