ValidationError:食谱验证失败:_listId:路径_listId是必需的

时间:2020-02-26 19:05:40

标签: javascript node.js mongodb express mongoose

我是node.js的新手,并尝试使用nodejs做一个菜谱宁静的API。因此,有一个列表和食谱应该在由ID选择的指定列表中。我正在尝试获取listId作为参数,但获得了undefined的价值。 邮递员显示错误:

{ “错误”:{ “ _listId”:{ “ message”:“路径_listId是必需的。”, “ name”:“ ValidatorError”, “属性”:{ “ message”:“路径_listId是必需的。”, “ type”:“必填”, “路径”:“ _ listId” }, “ kind”:“必需”, “路径”:“ _ listId” } }, “ _message”:“食谱验证失败”, “ message”:“食谱验证失败:_listId:路径_listId是必需的。”, “ name”:“ ValidationError” }

这是一个:

//Recipe model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RecipeSchema = new Schema({
    title: {
        type: String,
        required: true,
        minLength: 1,
        trim: true
    },
    _listId: {
        type: mongoose.Types.ObjectId,
        required: true
    }
});

module.exports = mongoose.model('Recipe', RecipeSchema);

食谱路线:

const express = require('express');
const controller = require('../controllers/recipes');
const router = express.Router();


router.get('/' , controller.get);
router.post('/' , controller.post);
router.patch('/:id' , controller.update);
router.delete('/:id' , controller.delete);

module.exports = router;

收件人控制器:

const Recipe = require('../models/recipe.model');
//get all recipes from specific list
module.exports.get = (req, res) => {
    Recipe.find({
        _listId: req.params.listId
    }).then((tasks) => {
        res.send(tasks);
    });
    console.log(req.params.listId); //undefined
};

//create new recipes in the list specified by id
module.exports.post = (req, res) => {
    let newRecipe = new Recipe({
        title: req.body.title,
        _listId: req.params.listId
    });
    console.log(req.params.listId); //undefined
    newRecipe.save().then((newRecipeDoc) => {
        res.send(newRecipeDoc);
    }).catch((e) => {
        res.send(e)
    });
};

我在其中配置路由的

和app.js文件

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const listRoutes  = require('./routes/list');
const recipeRoutes = require('./routes/recipe');
const keys = require('./config/keys');
const app = express();


mongoose.connect(keys.mongoURI,  {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
    .then(() => console.log('MongoDB connected'))
    .catch(error => console.log(error));

app.use(bodyParser.json());
app.use('/lists', listRoutes);
app.use('/lists/:listId/recipes', recipeRoutes);

module.exports = app;

List的get / post查询工作正常,但是对于Recipe我有undefined

1 个答案:

答案 0 :(得分:0)

好的,我发现问题可能对某人有帮助。 路线应为:

router.get('/:listId/recipes' , controller.get);
router.post('/:listId/recipes' , controller.post);
router.patch('/:listId/recipes:id' , controller.update);
router.delete('/:listId/recipes:id' , controller.delete);

和app.js路由应为

app.use('/lists', recipeRoutes);