首页 > 解决方案 > Req.body 在 node.js 中不可迭代

问题描述

我正在构建模拟 restful API 以更好地学习。我正在使用 MongoDB 和 node.js,为了测试我使用邮递员。

我有一个发送更新请求的路由器router.patch。在我的数据库中,我有name(字符串)、price(数字)和imageProduct(字符串 - 我保存图像的路径)。

我可以在邮递员上使用raw-format更新我的nameprice对象 ,但我不能用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
        });
    });
});

标签: node.jsmongodbrestapipostman

解决方案


使用 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);
}

推荐阅读