ipid
ipid

Reputation: 253

Delete id within nested array

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?

Upvotes: 0

Views: 125

Answers (2)

Rohail Najam
Rohail Najam

Reputation: 1041

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.

Upvotes: 2

ema
ema

Reputation: 5773

You need to use $pull:

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

Upvotes: 2

Related Questions