node.js - Req.body 在 node.js 中不可迭代
问题描述
我正在构建模拟 restful API 以更好地学习。我正在使用 MongoDB 和 node.js,为了测试我使用邮递员。
我有一个发送更新请求的路由器router.patch
。在我的数据库中,我有name
(字符串)、price
(数字)和imageProduct
(字符串 - 我保存图像的路径)。
我可以在邮递员上使用raw-format更新我的name
和price
对象 ,但我不能用form-data更新它。据我了解,在raw-form中,我使用数组格式更新数据。有没有办法在form-data中做到这一点?使用form-data的目的,我想上传一张新图片,因为我可以更新 的路径,但是我不能上传一个新的图片公用文件夹。我该如何处理?productImage
以原始形式更新数据的示例
[ {"propName": "name"}, {"value": "test"}]
路由器补丁
router.patch('/:productId', checkAuth, (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.updateMany({_id: id}, {$set: updateOps})
.exec()
.then(result => {
res.status(200).json({
message: 'Product Updated',
request: {
type: 'GET',
url: 'http://localhost:3000/products/' + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
err: err
});
});
});
解决方案
使用 for...of 是个好主意,但不能像循环对象属性那样使用它。值得庆幸的是,Javascript 有一些新函数可以将“对象的属性”转换为可迭代对象。
使用Object.keys:
const input = {
firstName: 'Evert',
}
for (const key of Object.keys(input)) {
console.log(key, input[key]);
}
您还可以使用 Object.entries 来键入键和值:
const input = {
firstName: 'Evert',
}
for (const [key, value] of Object.entries(input)) {
console.log(key, value);
}
推荐阅读
- amazon-web-services - 使用来自 Lambda 的 Node 签署 AWS WebSocket API POST 请求时出错
- python - 如何使用 gcloud-aio-storage 上传和获取自定义元数据?
- javascript - 数据更改时视图不更新,React,js
- python - 如何在python中将作为类属性的未知长度列表中的每个项目打印为字符串?
- java - 使用 JNA 将 C 代码映射到 Java 时,我应该为这种结构使用哪些类?
- spring-boot - 如何重新设计我的代码以减少代码冗余
- reactjs - 将 React.useReducer 重构为 redux。更新状态导致渲染问题
- android - 将 Android 房间数据库添加到项目后,任务:app:checkDebugDuplicateClasses FAILED 问题一次
- asp.net-core-mvc - 在 ASP.Net Core MVC 中调用 WebAPI
- twig - Twig - 路径和动态方法名