首页 > 解决方案 > MEAN 堆栈如何从数据库中查找 _id 以发送 PUT 请求

问题描述

我在从前端角度识别 mongoDB 中的“任务”时遇到问题。

这个问题与我的问题最相似,但在这里它只是说req.body.id并没有真正解释他们是如何得到的。

这个问题涉及我正在尝试做的事情:单击时更新集合中的一个文档。它在前端做什么并不重要。我只想将任务的状态文本从onclick更改"Active"为。"Completed"

首先,我创建一个任务并使用以下代码将其粘贴到我的数据库集合中:

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 被神奇地填写了!router.put('/:id')当我像这样从前端推送它时,我只是不确定如何将 id 传递给 nodejs 中的 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

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 是在数据库中自动创建的,所以在这里当我单击创建任务并输出到“卡”时,在tasksave()发布请求之后的控制台日志中taskId: undefined出现。这一切都很好,但我必须从前端任务接口发送一个唯一标识符,所以当我发送“放置”请求时,nodejs 会获得与“发布”相同的 id。

在这一点上我很困惑。

标签: node.jsangularmongodbdocumentput

解决方案


所以我终于想通了……万一它对某人有帮助,这就是最终奏效的方法:

首先,我将更新功能和(补丁而不是放置)请求移至触发服务:

触发服务

tasks: Task[] = [];

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

我还在触发器服务文件中创建了一个获取请求,以查找集合中的所有文档:

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

希望它可以帮助某人!


推荐阅读