验证错误:路径是必需的,但变量既不为null也不为空

时间:2019-10-14 12:02:02

标签: node.js mongodb express mongoose postman

我测试了我的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
}

1 个答案:

答案 0 :(得分:1)

在猫鼬文档中,我没有找到用于model.create的选项,您可以删除{new:true}并尝试吗?

相关问题