简体   繁体   中英

Put method not updating MongoDB in Angular7 with NodeJS on the backend

I have this Angular7 app with NodeJS and MongoDB on the backend. I have tested out my put method with Postman and it works perfectly. The error lies in my Angular service component or possibly the component module that is using the service. No error messages are being displayed in the console. I have isolated it down to this--all the data is making it to the service, so the breakdown is between the service component and the Node api. Here's the method in my service.ts file:

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

Here is my Api.JS method that works fine with 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))
    }) 
  })
})

Here is my component method that uses the services method:

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

Here is my template to show you what is going on there:

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

Any ideas what I have wrong? Thanks in advance guys.

You have to pass current _id as a first parameter and then whole object for update

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

I handled the problem. As there were no error messages with this, it made it more challenging to figure this one out. What I was missing was this inside of my service method:

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

In place of just data , you use {"savings": data} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM