簡體   English   中英

router.delete 返回空數組

[英]router.delete returns empty array

我正在嘗試添加一個函數,該函數通過 id 刪除 MongoDB 中的記錄,但結果我得到一個空數組並且該記錄沒有被刪除。

到目前為止,這是我的代碼:

//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)})
}

您在 deleteLine 函數中返回一個承諾,在您的路由器中實際運行它,您需要添加 then 塊,如下所示:

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

我找到了另一種方法來解決這個問題,而是調用 get 方法:

 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() }); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM