我测试了我的create方法是否有效,但是当我这样做时,它使我返回了此错误:
挑战服务的makeChallenge {ValidationError:挑战验证失败:minimumLevel:需要路径
minimumLevel
。,endDate:需要路径endDate
。startDate:需要路径startDate
,目标:路径objective
是必需的。,描述:路径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
}
答案 0 :(得分:1)
在猫鼬文档中,我没有找到用于model.create的选项,您可以删除{new:true}并尝试吗?