MEAN堆栈如何从数据库中找到_id以发送PUT请求

问题描述 投票:0回答:1

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

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

This question涉及到我正在尝试做的事情:单击即可更新集合中的一个文档。它在前端的作用并不重要。我只是想将任务的状态文本从"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);

    });
  }

在模板中,我填写了一个表格,数据立即输出到同一页面上的任务“卡”。

[当我从角度发送放置请求时,我在后端得到的响应恰好是我在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是在数据库中自动创建的,因此在此处单击创建任务时,在我对发布请求task进行save()之后,它会在taskId: undefined的控制台日志中输出到'card'过来。这一切都很好,但我必须从前端Task接口发送一个唯一的标识符,因此当我发送“ put”请求时,nodejs会获得与“ post”相同的ID。

我现在很困惑。

node.js angular mongodb document put
1个回答
0
投票

所以我终于弄清楚了……如果它可以帮助某人,那么这才是最终起作用的方法:

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

触发服务

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

Angular component

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

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

希望它可以帮助某人!

© www.soinside.com 2019 - 2024. All rights reserved.