【发布时间】:2020-02-11 01:17:24
【问题描述】:
我测试了我的 create 方法有效,但是当我这样做时,它又给了我这个错误:
challenge of challengeService { ValidationError: 挑战验证失败: minimumLevel: Path
minimumLevelis required., endDate: PathendDateis required., startDate: PathstartDateis required., Objective: Pathobjectiveis必需。,描述:路径description是必需的。,名称:路径name是必需的。
但是当我记录请求的正文时,所有这些参数都被填写了。当我遗漏一个参数时,错误变为只有那个需要的参数。
型号
import mongoose, { Document, Schema, Model } from 'mongoose';
export interface Challenge {
_id: any;
name: string;
description: string;
objective: string;
startDate: Date;
endDate: Date;
minimumLevel: number;
}
export interface ChallengeDocument extends Challenge, Document {}
const schema = new Schema(
{
name: { type: String, required: true },
description: { type: String, required: true },
objective: { type: String, required: true },
startDate: { type: Date, required: true },
endDate: { type: Date, required: true },
minimumLevel: { type: Number, required: true }
},
{ _id: true, timestamps: true }
);
export const model = mongoose.model<ChallengeDocument>('challenges', schema);
型号
import * as user from './modules/user/model';
import * as challenge from './modules/challenge/model';
import * as contract from './modules/contract/model';
export type Models = typeof models;
const models = {
user,
challenge,
contract
};
export default models;
服务
import { Router } from 'express';
import models from '../models';
const routes = Router();
const stringToDate = (string: string): Date => {
let subStringArray = string.split('-');
let intList: number[] = [];
subStringArray.forEach(str => {
intList.push(Number.parseInt(str));
});
console.log(intList);
let date: Date = new Date(intList[0], intList[1], intList[2]);
return date;
};
routes.post('/makeChallenge', async (req, res) => {
console.log(req.body);
const challenge = await models.challenge.model
.create(
{
name: req.body.name,
description: req.body.description,
objective: req.body.objective,
startDate: stringToDate(req.body.startDate),
endDate: stringToDate(req.body.endDate),
minimumLevel: Number.parseInt(req.body.minimumLevel)
},
{ new: true }
)
.catch(e => console.log('makeChallenge of challengeService', e));
res.send(challenge);
});
export default routes;
邮递员请求:
发帖到http://localhost:xxxx/makeChallenge
{
"name" : "TestChallenge",
"description" : "This is to test the api",
"objective" : "Make the api work",
"startDate" : "2019-9-23",
"endDate" : "2019-12-20",
"minimumLevel" : 1
}
【问题讨论】:
-
你得到
console.log(req.body);的值了吗? -
@Hiren 是的,我做到了,他们都很好地传递了
-
你可以创建没有接口的模型并尝试吗? export const model = mongoose.model('challenges', schema);
-
你也可以删除 {new: true} 吗?在猫鼬文档中,我没有找到 model.create 的这样一个选项
-
@SuleymanSah 移除接口并没有做任何事情,但移除 {new: true} 会做一些事情,现在我有一个新错误:在本地未授权执行命令跨度>
标签: node.js mongodb express mongoose postman