MeanStack:编辑特征“_id”的冲突将修改不可变字段“_id”

MeanStack: conflict on editing feature'_id' would modify the immutable field '_id'

我在这个 和其他地方看到了解决方案,但我确实按照说明进行操作,但我仍然遇到错误。我理解所有的逻辑,id 不能被替换,它们是不可变的,但在我的平均堆栈应用程序中,错误仍然存​​在。代码:

节点路由

  router.put("/:id" ,(req, res, next) => {
  const note = new Note({
    _id:req.body.id,
    project: req.body.project,
    note: req.body.note,
    date:req.body.date,

  });
  Note.updateOne({ _id: req.params.id }, note).then(result => {
    console.log(result)
    res.status(200).json({ message: "Update successful!" });
  });
});

前端编辑组件:

  ngOnInit(): void {
    this.notesForm=this.fb.group({
      note:['', Validators.required],
      project:['', Validators.required],
      date:[null,Validators.required]
    })
    this.route.paramMap.subscribe((paraMap:ParamMap)=>{
      if(paraMap.has('noteId')){
        this.mode='edit';
        this.noteId= paraMap.get('noteId');
        this.note=this.notePadService.getNote(this.noteId)
        .subscribe(noteData=>{
          this.note = {id: noteData._id, note: noteData.note, date: noteData.date, project: noteData.project};
        })
      }else{
        this.mode='create';
        this.noteId=null;
      }
    })
    this.getProjects();
  }
  onSubmit(){
    if(this.mode==='create'){
      this.notePadService.submitNotes(this.notesForm.value)
      console.log(this.notesForm.value);
      this.router.navigate(['/notes-listing'])
    }else{
      this.notePadService.updateNote(
        this.noteId,this.notesForm.value
      )
    }
  }

服务:

    getNote(id:string){
      return this.http.get<any>('http://localhost:3000/api/notes/'+id)
    }

updateNote(id:string,note:Notes){
    this.http.put('http://localhost:3000/api/notes/'+id,note)
    .subscribe(response=>console.log(response))
}

此外,我无法使用要编辑的值预先填充反应式表单:

  <label>Select a Project</label>
  <select (change)="test($event.target.value)" formControlName="project"
    class="form-control">
    <option
    *ngFor="let p of projects"
    [value]="p.name">{{ p.name }}</option>
  </select>
<!------->
<label for="notes">Note</label>
<textarea class="form-control"  formControlName="note" type="text" rows="4"></textarea>
<div class="input-group">
<mat-form-field appearance="fill">
  <mat-label>Choose a date</mat-label>
  <input formControlName="date" matInput [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<button mat-raised-button color="warn">Submit</button>
</form>

当我单击编辑按钮(在另一个组件中)时,我得到了正确的 URL 但没有值,并且在提交时,后端崩溃:

http://localhost:4200/edit/601ec21882fa6af20b454a8d

有人可以帮帮我吗?我很困惑,我无法理解错误,因为我已经完成了其他帖子建议的所有操作...

当您调用 updateOne 时,您已经将应该更新的 id 作为第一个参数传递。作为第二个参数,您传递的 note 应该只包含将要更新的属性,而不是 _id 本身:

  const note = {
    project: req.body.project,
    note: req.body.note,
    date:req.body.date,
  };