I'm working on a Library app and I've made it so when I click an "Add To Library" button it takes certain book values (book title, author, pages, etc.) and adds it to a Collections schema.
const collectionSchema = new mongoose.Schema({
title: {
type: String,
required: true,
unique: true,
},
author: {
type: String,
required: true,
},
status: {
type: String,
enum: ["plan", "current", "finish"],
default: "plan",
},
favorite: { type: Boolean, default: false },
image: {
type: Number,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
Here's my GET
router.get("/book/:title", function (req, res, next) {
const bookId = parseInt(req.params.title);
const book = data.PopularBooks.find((book) => book.id === bookId);
res.render("book", { book });
});
and I also have a router POST which saves the details of the book when I click the button.
router.post("/book/:title", [
// Validate and sanitize fields.
body("title", "Title must not be empty.")
.trim()
.isLength({ min: 1 })
.escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
const collection = new Collection({
title: req.body.title,
author: req.body.author,
status: "plan",
favorite: false,
image: req.body.image,
createdAt: Date.now(),
});
if (!errors.isEmpty()) {
// Get all authors and genres for form.
async.parallel((err, results) => {
if (err) {
return next(err);
}
res.render("book", {
title,
author,
createdAt,
errors: errors.array(),
});
});
return;
}
// Data from form is valid. Save statue update.
collection.save((err) => {
if (err) {
return next(err);
}
res.redirect("/users/profile");
});
},
]);
After I add the book to my collections I'm automatically taken to my profile page. Everything works great however when I go back to the same book I'm able to click the same button again and add the book to my profile multiple times. I've been trying to come up with ways to make each book unique so I can't add it again but everything I've tried hasn't worked out.