0

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",
}

1 Answer 1

2

When you save a reference to another collection you are storing directly the _id. So your model has this example data:

[
  {
    "_id":1,
    "booksList":[1,2,3,4],
    "name":"name1"
  }
]

Note how booksList is an array of numbers, not an array of objects {id: 1}.

So your query has to be without _id in the object _id: book._id. Something like this:

{$pull: {booksList: book._id}},

Check this example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.