Problem
1 Duplication of Data
2 Unnecessary Data has been added. ( Fixed - As shown below in image. )
Here, is the schema of my project ( Book ).
const BookSchema = new mongoose.Schema(
{
bookName: String,
bookPage: Number,
bookAuthor: String,
bookDescription: String,
ISBNNumber: {
unique:true,
type: String
},
bookCategory: {
type: String,
enum: Object.values(BOOK_CATEGORIES),
default: BOOK_CATEGORIES.FICTION,
},
bookSubCategory: {
type: String,
enum: Object.values(BOOK_SUBCATEGORIES),
default: BOOK_SUBCATEGORIES.ADVENTURE,
},
createdBy: {
type: mongoose.Types.ObjectId,
ref: "User",
},
publication: String,
recommendedBy: String,
bookImage:String,
bookImageId:String,
StartedBy: {
type: Date,
get: function (date) {
return formateDate(date);
},
set: function (date) {
return new Date(date);
},
},
finishedBy: {
type: Date,
get: function (date) {
return formateDate(date);
},
set: function (date) {
return new Date(date);
},
},
Link: String,
},
{ timestamps: new Date() }
);
function formateDate(date) {
return date.toISOString().slice(0, 10);
}
export default mongoose.model(“bookdata”, BookSchema);
Here, is the POST api through which I add the data from frontend ( Form ) to Database.
export const **createBooks** = async (req, res) => {
req.body.createdBy = req.user._id;
const newBook = { ...req.body };
// console.log(req.file);
if (req.file) {
const response = await cloudinary.v2.uploader.upload(req.file.path);
await fs.unlink(req.file.path);
newBook.bookImage = response.secure_url;
newBook.bookImageId = response.public_id;
}
const updatedBookImage = await BookModel.create(req.user._id, newBook);
if (req.file && updatedBookImage.bookImageId) {
await cloudinary.v2.uploader.destroy(updatedBookImage.bookImageId);
}
// console.log("Body", req.body);
const book = await BookModel.create(req.body);
res.status(StatusCodes.CREATED).json({ book });
};
GET API To show all books which I have added through POST API earlier.
export const getAllBooks = async (req, res) => {
// console.log(req.user);
const books = await BookModel.find({ createdBy: req.user._id });
// console.log("GET All books");
res.status(StatusCodes.OK).json({ books });
};
I have confirmed that in frontend part there is no problem as API is called only once.
Has anyone been facing this kind of problem !?