簡體   English   中英

如何使用刪除 API 刪除 MongoDB 中的數組條目?

[英]How can I delete an array entry in MongoDB with a delete API?

我正在構建一個管理時間敏感任務的應用程序。 我有 API 來創建任務和檢索任務,我目前正在嘗試讓我的刪除 API 工作。

一名員工在 MongoDB 中有一個數組,其中包含帶有文本的待辦事項任務,我試圖在 SoapUI 中按 ID 刪除該任務。 使用我當前的代碼,刪除請求會在大約一分鍾后超時。

這是我當前的刪除 API

router.delete("/:empId/tasks/:id", async (req, res) => {
  try {
    Employee.findByIdAndDelete(
      {
        empId: req.params.empId,
      },

      {
        $pull: {
          todo: {
            _id: req.params.id,
          },
        },
      }
    );
  } catch (e) {
    console.log(e);
    res.status(500).send({
      message: "Internal server error: " + e.message,
    });
  }
});

當前模式

let itemSchema = new Schema({
  text: { type: String },
  _id: { type: String },
});

任務服務

  deleteTask(empId: number, task: string, _id: number): Observable<any> {
    return this.http.delete('/api/employees/' + empId + '/tasks/' + _id);
  }

以及 MongoDB 中的員工文檔示例

{"_id":{"$oid":"61797a51d15ad09b88d167af"},"empId":"1012", "firstName":"web","lastName":"developer","__v":1,"done":[],"todo":[{"_id":"1","text":"test"}]}

當您使用 findByIDAndDelete 時,它​​會刪除整個文檔。 您需要的是使用update() / findOneAndUpdate() / findByIdAndUpdate()更新該特定文檔。 此外,您應該等待/使用回調來返回值,例如,

collection.findOneAndUpdate({_id:docId },{
        $pull: {"todo":{"_id":yourId} },
      },
      function(error, data){
           if(error){ return error}
           else {return data}
})

暫無
暫無

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

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