skip to Main Content

I’m trying to delete "627cfc7a9765ad8c65d03798" in ‘Rooms’

obje:

    _id:627b93d43c14903de411d915
    name:"Awesome Hotel Updated"
    type:"hotel"
    city:"berlin"
    tittle:"Best Hotel in the City"
    rooms:[
     0:"627cf8c384aa07450d629279"
     1:"627cfc7a9765ad8c65d03798"
    ]

function :

    export const deleteRoom = async (req, res, next) => {
        try {
            await Room.findByIdAndDelete(req.params.id);
            await Hotel.findByIdAndUpdate(req.params.hotelId, {
                $pull: { rooms: req.params.id }
            })
            res.status(200).json("Room has been deleted.");
        } catch (err) {
            next(err)
        }
    }

Help me delete items in ‘Rooms’!

2

Answers


  1. Probably you are looking for this:

    const object = {
         _id:627b93d43c14903de411d915,
        name:"Awesome Hotel Updated",
        type:"hotel",
        city:"berlin",
        tittle:"Best Hotel in the City",
        rooms:[
         {room_id:"627cf8c384aa07450d629279"},
         {room_id:"627cfc7a9765ad8c65d03798"}
        ]
    }
    

    Here in this "object" you should store your room id as above mentioned "room_id",
    So this will help you to filter your rooms easy

    Instead Try this:

      export const deleteRoom = async (req, res, next) => {
            try {
                const room = await Room.findById(req.params.id);
                const hotel = await Hotel.findById(req.params.hotelId)
                await room.remove()
                hotel.rooms.splice(hotel.rooms.findIndex(a => a.room_id === room.id) , 1)
                
    
                res.status(200).json("Room has been deleted.");
            } catch (err) {
                next(err)
            }
        }
    
    Login or Signup to reply.
  2. The following code does work.

    db.collection.update({
      "city": "berlin"
    },
    {
      $pull: {
        "rooms": "627cf8c384aa07450d629279"
      }
    })
    

    Maybe you’re getting an error somewhere inside the findByIdAndUpdate method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search