Tìm kiếm trang web

node.js - Lỗi khi chạy mã cập nhật mongoose ( router.patch() )


Tôi gặp lỗi khi chạy mã router.patch() để cập nhật một sản phẩm trên cơ sở dữ liệu mongoose dựa trên đám mây. Tôi đang sử dụng Postman để mô phỏng việc cập nhật. Lỗi của Postman hiển thị, "req.body[Symbol.iterator] không phải là một hàm." Đây là mã liên quan:

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);

Mọi sự giúp đỡ đều sẽ được trân trọng. :-)

Câu trả lời #1

Như tôi đã bình luận, phần này có khả năng là vấn đề của bạn:

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

Vì req.body là một Object, tôi nghĩ bạn muốn:

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

Hoặc thứ gì đó tương tự.