尝试POST请求时出现猫鼬验证错误

时间:2020-05-06 17:21:41

标签: javascript node.js mongodb mongoose

我正在尝试制作一个包含类别和笑话的媒体应用。

当我向/ api / category / new发送POST请求时,出现此错误:

pip install --upgrade pandas

对于{ message: 'Path `joke` is required.', name: 'ValidatorError', properties: [Object], kind: 'required', path: 'joke', value: undefined, reason: undefined, [Symbol(mongoose:validatorError)]: true }, 路径,我也遇到相同的错误(在此错误下方),但不是joke路径。

模型

user

路线

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Joke Schema
const jokeSchema = new Schema({
  user: { type: String , required: true},
  joke: { type: String, required: true, maxlength: 100 },
});

// Category Schema
const categorySchema = new Schema({
  name: { type: String, required: true, unique: true },
  description: { type: String, required: false },
  likes: { type: Number },
  jokes: [jokeSchema],
});

module.exports = mongoose.model("category", categorySchema);
module.exports = mongoose.model("joke", jokeSchema);

1 个答案:

答案 0 :(得分:0)

您正在覆盖module.exportsmodels/model.js中有两个:

module.exports = mongoose.model("category", categorySchema);
module.exports = mongoose.model("joke", jokeSchema);

因此const Category = require('../models/model')时,您得到的是jokeSchema而不是类别,因此,验证错误与该笑话模式有关。

只需删除module.exports = mongoose.model("joke", jokeSchema);,它就可以正常工作,或者如下操作:

models / models.js

module.exports = {};
module.exports.category = mongoose.model('category', categorySchema);
module.exports.joke = mongoose.model('joke', jokeSchema);

routes / CategoryRouter.js

//category model
const Category = require('../models/model').category;