我正在尝试从数据库(Mongoodb)更新数据,但当我尝试在邮递员上检查它时,我收到此错误:“错误: ValidationError:持续时间:转换为数字失败,路径\”持续时间\“的值\"NaN\”,日期:转换为日期失败的值\"NaN\“路径\”日期\“,用户名:路径username是必需的。,描述:需要路径description。”
这是我的路线:
const router = require('express').Router();
let Exercise = require('../models/exercise.model');
router.route('/').get((req, res) =>{
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) =>{
const username = req.body.username,
description = req.body.description,
duration = Number(req.body.duration),
date = Date.parse(req.body.date);
const newExercise = new Exercise({
username,
description,
duration,
date,
});
newExercise.save()
.then(() => res.json('Exercise added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
// See the Information of exercises in the database
router.route('/:id').get((req, res) =>{
Exercise.findById(req.params.id)
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json('Error: ' + err));
});
// Delete exercises from the database
router.route('/:id').delete((req, res) =>{
Exercise.findByIdAndDelete(req.params.id)
.then(() =>res.json('Exercise was deleted!'))
.catch(err => res.status(400).json('Error: ' + err));
});
// Update the exercise to the database
router.route('/update/:id').post((req, res) => {
Exercise.findByIdAndUpdate(req.params.id)
.then(exercise => {
exercise.username = req.body.username;
exercise.description = req.body.description;
exercise.duration = Number(req.body.duration);
exercise.date = Date.parse(req.body.date);
console.log(typeof(exercise.date));
exercise.save()
.then(() => res.json('Exercise updated!'))
.catch(err => res.status(400).json('Error: ' + err));
})
.catch(err => res.status(400).json('Error: ' + err));
});
// Export the route
module.exports = router;这是我的方案:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const exerciseSchema = new Schema({
username: {type: String, required: true},
description: {type: String, required: true},
duration: {type: Number, required: true},
date: {type: Date, required: true},
}, {
timestamps: true,
});
const Exercise = mongoose.model('Exercise', exerciseSchema);
module.exports = Exercise;请帮我解决这个问题,谢谢
发布于 2020-07-18 14:20:04
在使用findByIdAndUpdate的update块中,将其替换为findById,或者如果要使用findByIdAndUpdate,则在参数中提供所有更新详细信息
findByIdAndUpdate(req.params.id, {
username = req.body.username,
description = req.body.description,
duration = Number(req.body.duration),
date = Date.parse(req.body.date),
},
function(err,docs){
if(err) console.log(err)
else console.log("Updated")
})或者如果使用fingById
Exercise.findById(req.params.id)
.then(exercise => {
exercise.username = req.body.username,
exercise.description = req.body.description,
exercise.duration = Number(req.body.duration),
exercise.date = Date.parse(req.body.date)
})发布于 2020-10-01 22:32:50
刚刚在Postman中遇到了这个问题,这是因为我忘记了将原始正文类型从Text更改为JSON。即使发送的是有效的JSON,原始数据的类型也是不正确的。
https://stackoverflow.com/questions/62201020
复制相似问题