错误"/>
尝试POST请求时猫鼬验证错误
我正在尝试制作一个包含类别和笑话的媒体应用。
当我向/ api / category / new发出POST请求时,出现此错误:
{
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);
路线
const router = require("express").Router();
//category model
const Category = require("../models/model");
// POST /api/category/new : Creates a new cartgory
router.post("/new", (req, res) => {
const newCategory = new Category({
name: req.body.name,
description: req.body.description,
likes: 0,
jokes: [],
});
newCategory
.save()
.then((category) => res.json(category))
.catch((err) => console.log(err));
});
module.exports = router;
回答如下:您正在覆盖module.exports
。您在models/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;
更多推荐
尝试POST请求时猫鼬验证错误
发布评论