0

So far I can only manage to delete the first id (in this case the id with "12345").

Im trying to delete the row with id 2 within books-array

 Libary Table: 

   {
    "_id": {
        "$oid": "12345"
    },
    "libaryName": "A random libary",
    "Books": [       
        {
            "_id": {
                "$oid": "1"
            }
            "bookTitle": "Example",
            "TotalPages": "500"                 
        },
        {
            "_id": {
                "$oid": "2"
            }
            "bookTitle": "Delete Me",
            "TotalPages": "400"                 
        }
    ]
}

My delete code:

router.delete('/:id', (req, res) => {
  Libary.remove({ _id: req.params.id })
    .then(() => {
      //redirect
    });
});

How can I reach and delete the book row where the id is 2?

2 Answers 2

2

You need to use $pull opertator

router.delete('/:id', (req, res) => {
  Libary.update({ _id: req.params.id }, //This is the Id of library Document
  { $pull: { "Books": {"_id":2) } } }) // This will be the Id of book to be deleted
    .then(() => {
      //redirect
    });
});

Hope it helps.

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

2 Comments

Thanks a lot. Btw, does it matter if I use quotation marks or not? Like at "Books".
In Javascript it doesn't . I tested this query on mongo shell and copied it from there.
2

You need to use $pull:

Library.update(
  { },
  { $pull: { Books: { _id: 2 } } }
)

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.