node.js - TypeError:预期的字符串,但收到数组邮递员
问题描述
我试图发送具有多个同名字段的表单数据,我收到“TypeError:预期的字符串但收到的数组”。
我认为问题出在邮递员身上,我希望有多个参与者字段,并且将这些字段添加到应该添加到数组中。
// this is from models/Battle
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const BattleSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
date: {
type: Date,
default: Date.now
},
category: {
type: Number,
required: true // this will come from the selected category
},
winner: {
type: Number,
default: 0
},
status: {
type: Number,
default: 0 // 0 means the battle is closed, 1 means the battle is open for votes, the status will stay 0 until all participants dropped
},
participants: [
{
participant: {
type: Schema.Types.ObjectId,
required: true
}
}
]
});
module.exports = Battle = mongoose.model('battles', BattleSchema);
//this is from routes/api/battles
// @route POST api/battles
// @desc Create battle
// @access Private
router.post(
'/create-battle',
passport.authenticate('jwt', { session: false }),
(req, res) => {
const { errors, isValid } = validateBattleInput(req.body);
// Check Validation
if (!isValid) {
// If any errors, send 400 with errors object
return res.status(400).json(errors);
console.log(errors);
}
const newBattle = new Battle({
user: req.user.id,
category: req.body.category,
participant: req.body.participant
});
//save
newBattle.save().then(battle => {
// const participant = req.body.participant;
const participant = req.body.participant;
// add participants to array
battle.participants.push( participant );
console.log(typeof req.body.participant);
// get the inserted id
const battleId = battle._id;
res.json(battle);
});
}
);
// this is battle validation
const Validator = require('validator');
const isEmpty = require('./is-empty');
var bodyParser = require('body-parser');
module.exports = function validateBattleInput(data) {
let errors = {};
data.category = !isEmpty(data.category) ? data.category : '';
data.participant = !isEmpty(data.participant) ? data.participant : '';
if (Validator.isEmpty(data.category)) {
errors.category = 'Category field is required';
}
// if (Validator.isEmpty(data.challenger)) {
// errors.challenger = 'Challenger field is required';
// }
if (Validator.isEmpty(data.participant)) {
errors.participant = 'Participant field is required';
}
return {
errors,
isValid: isEmpty(errors)
};
};
解决方案
TypeError:预期的字符串,但收到的数组。--- 在邮递员和终端窗口中引发错误。我怀疑这可能是用户架构定义不匹配
请检查您的用户模型用户架构,例如名称:{ type: String, required: true } 它收到的内容超出预期。
推荐阅读
- javascript - 更新 angular-devkit 并失败:Microsoft.AspNetCore.SpaServices[0]
- json - Javascript Base64 解码到无效的 JSON 输出
- c# - 扩展 IEnumerable 的 Select 以将源包含在选择器中
- php - 爆炸函数在数组的第 0 个索引处返回空值
- python - 尽管已安装模块,但 jupyter 笔记本中未定义 skimage
- node.js - server.use(express.static(path.join(__dirname, 'public'))); 不工作
- javascript - React - 列表中的每个孩子都应该有一个唯一的“关键”道具
- joomla - 类别上的 Joomla 斜杠
- c# - 如何检查字符串是否不等于多个字符串
- docker - k8s 集群中的两个 coredns Pod 处于挂起状态