【问题标题】:Error running mongoose update code ( router.patch() )运行猫鼬更新代码时出错( router.patch() )
【发布时间】:2018-04-24 04:17:40
【问题描述】:

我在运行 router.patch() 代码以更新基于云的猫鼬数据库上的产品时遇到错误。我正在使用 Postman 来模拟更新。邮递员的错误显示,“req.body[Symbol.iterator] 不是函数。”以下是相关代码:

Products.js:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');

const Product = require('../models/product');


    router.patch('/:productId', (req, res, next) => {
        const id = req.params.productId;
        // don't want to update both fields if not needed
        const updateOps = {};
        // loop through all the operations of the request body
        for (const ops of req.body) {
            updateOps[ops.propName] = ops.value;
        }
        Product.update({_id: id}, { $set: updateOps })// $set is a mongoose object
            .exec()
            .then(result => {
                console.log(result);
                res.status(200).json(result);
            })
            .catch(err => {
                console.log(err);
                res.status(500).json({
                    error: err
                });
            });
            {req.body.newName, price, req.body.newPrice} ;
            res.status(200).json({
            message: 'Updated product',
        });
    });


module.exports = router

Product.js:

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: String,
    price: Number
});
// export the schema into the Mongoose model
module.exports = mongoose.model('Product', productSchema);

任何帮助将不胜感激。 :-)

【问题讨论】:

  • for (const ops of req.body) { updateOps[ops.propName] = ops.value; } 我想这是你的问题。
  • 我该怎么办?

标签: node.js typescript express


【解决方案1】:

正如我评论的,这部分可能是你的问题:

for (const ops of req.body) {
  updateOps[ops.propName] = ops.value;
}

由于req.body 是一个对象,我想你想要:

for (let [key, value] of Object.entries(req.body)){
  updateOps[key.propName] = value;
}

或类似的东西。

【讨论】:

  • 我不确定我是否理解如何将您的答案翻译成我的脚本。我用 req.body 替换“对象”吗?我是使用术语 [key, value] 还是将它们替换为特定于我的代码的内容?
  • 好的,我一会儿试试。
猜你喜欢
  • 1970-01-01
  • 2012-03-28
  • 2020-07-13
  • 2021-12-15
  • 2018-12-16
  • 2015-04-05
  • 2016-05-14
  • 2014-04-26
  • 2017-03-08
相关资源
最近更新 更多