![](/img/trans.png)
[英]How to define PUT method for complex json objects for updating records in mongoDB using nodejs scripts?
[英]Put method not updating MongoDB in Angular7 with NodeJS on the backend
我在后端有這個帶有NodeJS和MongoDB的Angular7應用程序。 我已經用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>
有什么主意我錯了嗎? 在此先感謝大家。
您必須傳遞當前的_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))
})
})
})
我解決了這個問題。 由於沒有與此相關的錯誤消息,因此弄清楚這一點變得更具挑戰性。 我所缺少的是我的服務方法內部的內容:
return this._http.put(url, {"savings": data}, httpOptions).subscribe(data =>
{console.log("PUT request successful ", data)})
僅僅是在原地的data
,您可以使用{"savings": data}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.