gpt4 book ai didi

javascript - Node Js findByIdAndUpdate 函数未在数据库中更新

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:14 25 4
gpt4 key购买 nike

我通过创建 API 并在 Angular 2 服务中调用它们,根据 Nodejs 中的 id 更新产品。

routes/products.js

router.post('/:id', function(req, res, next) {

Products.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if(err){
res.json({success: false, msg:'Failed updating products'});
} else {
res.json({success: true, msg:'success updating products'});

}
});
});

这就是我传递 postman 的方式:POST 请求

{
"id":"596df0ffcb429a586ef6c0bf",
"category_id": "596ddb165314d15618795826",
"product_name":"Laysssss masala",
"product_price":5,
"product_image":"image1ddd",
"product_desc":"Yummyddsd",
"product_status":"Activedddd"
}

产品似乎保存在数据库中。

同样,当我在 Angular 下调用服务并在浏览器中尝试时,我在 broswer 中得到“产品更新成功”,但没有反射(reflect)在数据库中。

组件.ts

onSaveConfirm(event) {
if (window.confirm('Are you sure you want to save?')) {
// var prodId = event.newData['_id']
//console.log(event.newData)
this.productService.productUpdate(event.newData).subscribe(data => {
if (data.success) {
console.log('Edited success')
this.flashMessage.show('Product updated successfully', { cssClass: 'alert-success', timeout: 3000 });
this.router.navigate(['/category-items']);
} else {
console.log('failure edited...')
this.flashMessage.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
this.router.navigate(['/category-items']);
}
});
event.confirm.resolve(event.newData);
} else {
event.confirm.reject();
}

}

产品.service.ts

 productUpdate(products) {
var prodId = products['_id'];
console.log(products)
let prodUrl = "http://localhost:8080/products/" + prodId
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let prodIdObj = JSON.stringify({ products: products })
return this.http.post(prodUrl, prodIdObj, { headers: headers })
.map((response: Response) => response.json())
.do(data => JSON.stringify(data))
.catch(this.handleError);
}

最佳答案

也许你的问题在这里:

product.service.ts中:

productUpdate(products) {
//skipped
let prodUrl = "http://localhost:8080/products/" + prodId
//skipped
}

products.js

router.post('/:id', function(req, res, next) {

Products.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if(err){
res.json({success: false, msg:'Failed updating products'});
} else {
res.json({success: true, msg:'success updating products'});

}
});
});

将其更改为:

router.post('products/:id', function(req, res, next) {

//do something
});

关于javascript - Node Js findByIdAndUpdate 函数未在数据库中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45230355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com