簡體   English   中英

MEAN堆棧如何從數據庫中找到_id以發送PUT請求

[英]MEAN stack how to find _id from database to send a PUT request

我在從前端角度識別 mongoDB 中的“任務”時遇到問題。

這個問題與我的問題最相似,但在這里它只是說req.body.id並沒有真正解釋他們是如何得到的。

這個問題涉及我想要做的事情:單擊更新集合中的一個文檔。 它在前端做什么並不重要。 我只想將任務的狀態文本從"Active"更改為"Completed" onclick。

首先,我創建一個任務並使用以下代碼將其粘貼到我的數據庫集合中:

createTask(): void {
    const status = "Active";
    const taskTree: Task = {
      _id: this._id,
      author: this.username,
      createdBy: this.department,
      intendedFor: this.taskFormGroup.value.taskDepartment,
      taskName: this.taskFormGroup.value.taskName,
      taskDescription: this.taskFormGroup.value.taskDescription,
      expectedDuration: this.taskFormGroup.value.expectedDuration,
      status: status
    };   
    this.http.post("/api/tasks", taskTree).subscribe(res => {
      this.taskData = res;
    });
  }

當我把這篇文章發到后端時,_id 被神奇地填滿了! 當我像這樣從前端推送時,我不確定如何將 id 傳遞給 nodejs router.put('/:id')的 put 請求:

completeTask(): void {
    const status = "Completed";
    const taskTree: Task = {
      _id: this._id,
      author: this.username,
      createdBy: this.department,
      intendedFor: this.taskFormGroup.value.taskDepartment,
      taskName: this.taskFormGroup.value.taskName,
      taskDescription: this.taskFormGroup.value.taskDescription,
      expectedDuration: this.taskFormGroup.value.expectedDuration,
      status: status
    }; 
    console.log(taskTree);


    this.http.put("/api/tasks/" + taskTree._id, taskTree).subscribe(res => {
      this.taskData = res;
      console.log(res);

    });
  }

在模板中,我填寫了一個表單,數據會立即輸出到同一頁面上的任務“卡片”。

當我從 angular 發送 put 請求時,我在后端得到一個響應,就像我在task-routes.js要求的響應task-routes.js

router.put("/:id", (req, res, next) => {
    const taskData = req.body;
    console.log(taskData);

    const task = new Task({
        taskId: taskData._id,
        author: taskData.author,
        createdBy: taskData.createdBy,
        intendedFor: taskData.intendedFor,
        taskName: taskData.taskName,
        taskDescription: taskData.taskDescription,
        expectedDuration: taskData.expectedDuration,
        status: taskData.status
    })

    Task.updateOne(req.params.id, {
        $set: task.status
    },
    {
        new: true
    },
    function(err, updatedTask) {
        if (err) throw err;
        console.log(updatedTask);   
    }
    )

});

我得到的更新信息的一般響應是:

{
  author: 'there's a name here',
  createdBy: 'management',
  intendedFor: null,
  taskName: null,
  taskDescription: null,
  expectedDuration: null,
  status: 'Completed'
}

現在我知道 _id 是在數據庫中自動創建的,所以當我點擊創建任務時,它會輸出到“卡片”,在我在 post 請求上save()后,在task的控制台日志中, taskId: undefined出現了。 這一切都很好,但我必須從前端任務界面發送一個唯一標識符,因此當我發送“放置”請求時,nodejs 獲得與“發布”相同的 ID。

在這一點上我很困惑。

所以我終於想通了...萬一它對某人有幫助,這就是最終有效的方法:

首先,我將更新函數和(補丁而不是放置)請求移動到我的觸發器服務:

觸發服務

tasks: Task[] = [];

updateTask(taskId, data): Observable<Task> {    
    return this.http.patch<Task>(this.host + "tasks/" + taskId, data);
  }

我還在觸發器服務文件中創建了一個 get 請求來查找集合中的所有文檔:

getTasks() {
    return this.http.get<Task[]>(this.host + "tasks");
  }

角分量

在 ngOnInit 中獲取任務以在組件加載時列出它們:

ngOnInit() {
    this.triggerService.getTasks().subscribe(
      tasks => {
        this.tasks = tasks as Task[];
        console.log(this.tasks);
      },
      error => console.error(error)
    );
}

更新:

completeTask(taskId, data): any {
    this.triggerService.updateTask(taskId, data).subscribe(res => {
      console.log(res);
    });
  }

角度模板 (html)

<button mat-button
            class="btn btn-lemon"
            (click)="completeTask(task._id)"
            >Complete Task</button>
// task._id comes from `*ngFor="task of tasks"`, "tasks" being the name of the array 
//(or interface array) in your component file. "task" is any name you give it, 
//but I think the singular form of your array is the normal practice. 

后端路由

獲取所有任務:

router.get("", (req, res, next) => {
  Task.find({})
    .then(tasks => {
      if (tasks) {
        res.status(200).json(tasks);
      } else {
        res.status(400).json({ message: "all tasks not found" });
      }
    })
    .catch(error => {
      response.status(500).json({
        message: "Fetching tasks failed",
        error: error
      });
    });
});

更新指定文檔中的 1 個字段(狀態從“活動”到“已完成”):

router.patch("/:id", (req, res, next) => {
  const status = "Completed";

  console.log(req.params.id + " IT'S THE ID ");

  Task.updateOne(
    { _id: req.params.id },
    { $set: { status: status } },
    { upsert: true }
  )
    .then(result => {
      if (result.n > 0) {
        res.status(200).json({
          message: "Update successful!"
        });
      }
    })
    .catch(error => {
      res.status(500).json({
        message: "Failed updating the status.",
        error: error
      });
    });
});

希望它可以幫助某人!

暫無
暫無

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

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