node.js - Put 方法不在后端使用 NodeJS 更新 Angular7 中的 MongoDB

标签 node.js angular mongodb mongoose angular7

我有这个 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))
    }) 
  })
})

这是我使用服务方法的组件方法:

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> 

有什么想法我错了吗?提前谢谢大家。

最佳答案

你必须传递当前的 _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))
    }) 
  })
})

关于node.js - Put 方法不在后端使用 NodeJS 更新 Angular7 中的 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859602/

相关文章:

node.js - AWS抛出CORS

mongodb - 获取 mongo shell 脚本的输出

mongodb - 为数组元素指定多个条件

node.js - 更新到 Mac OSX 10.9.4 后找不到 npm 命令

node.js - 查询数组中的匹配日期

node.js - Bot Framework - 在 NodeJS 中处理用户发送的图像

javascript - 从对象数组中删除元素后,Angular 2 View 未更新

node.js - 环回 postgresql 关系 "public.acl"

angular - 如何在运行时更改 ng-zorro 主题

javascript - 按最高计数聚合