Pablo G
Pablo G

Reputation: 199

router.delete returns empty array

I'm trying to add a function that deletes a record in MongoDB by the id, but I'm getting an empty array as a result and the record is not deleted.

Here is my code so far:

//router
router.delete('/comandas/:id', (req, res) => {
  deleteLine(req.params.id)
  res.status(500).end()
  });
});
//delete function
const objectId = require('mongodb').ObjectID;

const init = () =>
  MongoClient.connect(connectionUrl, { useNewUrlParser: true, useUnifiedTopology: true }).then((client) => {
    db = client.db(dbName)
  })

const deleteLine = (id) => {
  const collection = db.collection('comanda')
  return collection.deleteOne({"_id": objectId(id)})
}

Upvotes: 1

Views: 110

Answers (2)

Pablo G
Pablo G

Reputation: 199

I found another way to solve this calling the get methods instead:

router.get('/comandas/:id/delete', (req, res) => {
   deleteLine(req.params.id)
  .then( () => {
    console.log(req.params.id + ' deleted')
    res.status(500).end()
  })
  .catch((err) => {
    console.log(err)
    res.status(500).end()
  });
});

Upvotes: 0

SuleymanSah
SuleymanSah

Reputation: 17868

You are returning a promise in deleteLine function, in your router to actually make it run you need to add then block like this:

  deleteLine(req.params.id).then(result => {
    console.log(result);    
    //todo: send response
  })
  .catch(err => {
    console.log(err);
      //todo: send error response
  })

Upvotes: 1

Related Questions