Book Model
const BookSchema = new mongoose.Schema({
isbn: {
type: Number,
required: true,
unique: true,
},
name: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Book", BookSchema );
Library Model
const LibrarySchema= new mongoose.Schema({
booksList: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Book",
},
],
name: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Library", LibrarySchema);
deleteBook
router.delete("/:libraryID/book/:isbn", async (req, res) => {
try {
const book = await Book.findOne({
isbn: req.params.isbn,
});
await Library.findOneAndUpdate(
{_id: req.params.libraryID},
{$pull: {booksList: {_id: book._id}}},
{new: true},
function (error, data) {
console.log("Error: " + error);
if(!error) {
res.status(200).send({
success: true,
message: "Book removed successfully",
});
}
}
);
} catch (err) {
res.send({success: false, error: err.message});
}
});
I trying to pull a book with the object id from booksList array but nothing is working. I have tried almost every solution available on internet for this but nothing is working.
I always get this response but the book remains in the booksList array always.
{
success: true,
message: "Book removed successfully",
}