【问题标题】:Put method not updating MongoDB in Angular7 with NodeJS on the backend在后端使用NodeJS的Put方法不更新Angular7中的MongoDB
【发布时间】:2019-07-18 11:12:58
【问题描述】:

我有这个 Angular7 应用程序,后端带有 NodeJS 和 MongoDB。我已经用 Postman 测试了我的 put 方法,它运行良好。错误在于我的 Angular 服务组件或可能是使用该服务的组件模块。控制台中未显示任何错误消息。我已将其隔离到这一点——所有数据都在进入服务,因此故障发生在服务组件和 Node api 之间。这是我的 service.ts 文件中的方法:

updateSavings(pin: string, data){
const url = `api/accounts/${pin}`;
console.log(data);
return this._http.put(url, data, httpOptions)
  .pipe(catchError(this.handleError)
  );
}

这是我的 Api.JS 方法,可以很好地与 Postman 配合使用:

router.put('/accounts/:pin', function(req, res, next) {
  Accounts.findOneAndUpdate({pin: req.params.pin}, {savings: 
  req.body.savings}).then(function() {
  //console.log(req.body.savings);
  Accounts.findOne({pin:req.params.pin}).then(function(account){
  //console.log(res.send(account))
    }) 
  })
})

这是我使用 services 方法的组件方法:

depositSavings(data){
  let y = this.accountsService.updateSavings(this.appComponent.rightPin, 
  data);
  console.log(this.appComponent.rightPin);
  return y;
  }
} 

这是我的模板,向您展示那里发生了什么:

<input 
  type="text"
  id="input"
  [(ngModel)]="data"
  [ngModelOptions]="{standalone: true}">
  <br><br>
  <button (click)="depositSavings(data)">Submit</button> 

有什么想法我错了吗?提前谢谢各位。

【问题讨论】:

    标签: node.js angular mongodb mongoose angular7


    【解决方案1】:

    您必须将当前 _id 作为第一个参数传递,然后将整个对象传递给更新

    router.put('/accounts/:pin', function(req, res, next) {
      Accounts.findOneAndUpdate(req.params._id, {pin: req.params.pin, savings: 
      req.body.savings}).then(function() {
      //console.log(req.body.savings);
      Accounts.findOne({pin:req.params.pin}).then(function(account){
      //console.log(res.send(account))
        }) 
      })
    })
    

    【讨论】:

    • 不幸的是,这并没有成功。随着这些变化,它仍然可以在 Postman 中使用,但不能在 Angular 应用程序中使用。
    • 我知道这是节点。它在我的 api.js 文件中。在 angular 未与 put 上的 api 通信的情况下,问题仍然存在。我有一个在角度应用程序中运行良好的 get 方法。但是这个 put 方法不起作用。
    【解决方案2】:

    我处理了这个问题。由于没有错误消息,因此弄清楚这一点变得更具挑战性。我缺少的是我的服务方法中的这个:

    return this._http.put(url, {"savings": data}, httpOptions).subscribe(data => 
    {console.log("PUT request successful ", data)})
    

    您使用{"savings": data} 代替data

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 1970-01-01
      • 2016-02-24
      • 2021-11-03
      • 1970-01-01
      • 2014-09-25
      • 2015-11-18
      • 2014-05-27
      • 1970-01-01
      相关资源
      最近更新 更多