【发布时间】: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