Мой код node js не влияет на ключевое слово "требовать" - PullRequest
0 голосов
/ 02 августа 2020

Я начинаю изучать node.js, REST API и MongoDB, следуя некоторым онлайн-ресурсам. Я попытался использовать ключевое слово «require» в моем следующем коде, чтобы пользователям не разрешалось вводить пустое значение:

ninjas. js (создать схему и модели)

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

//create Schema and model
const NinjaSchema = new Schema({
    name:{
        type: String,
        require: [true,'Name field is required']
    },
    rank:{
        type: String,
        require: [true,'This field is required']
    },
    available:{
        type: Boolean,
        default: false,
        require: [true,'This field is required']
    }
    //add in geo loction
});

const Ninja = mongoose.model('hi ninja',NinjaSchema);

module.exports = Ninja;

Ниже приведен код обработки API:

api. js

const express = require('express');
const Ninja = require('../models/ninjas');
const router = express.Router();

//get a list of ninjas from the database
router.get('/ninjas',(req,res,next)=>{
    res.send({type: 'GET'});
})

//add a new ninjas to the database
router.post('/ninjas',(req,res,next)=>{
    //create a Ninja object and save it to DB
    Ninja.create(req.body).then((ninja) => {
        res.send(ninja)
    }).catch(next);
})

//update a ninjas in the database
router.put('/ninjas/:id',(req,res,next)=>{
    res.send({type: 'PUT'});
})

//delete a ninjas from the database
router.delete('/ninjas/:id',(req,res,next)=>{
    res.send({type: 'DELETE'});
})

module.exports = router;

Ниже приведена основная программа:

index. js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

//set up express app
const app = express();

//connect to mondodb
mongoose.connect("mongodb://localhost/ninjago",{
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
mongoose.Promise = global.Promise;

//body parser middleware
app.use(bodyParser.json());

//initialize routes
app.use('/api',require('./routes/api'));

//error handling middleware
app.use((err,req,res,next) => {
    //console.log(err);
    res.status(422).send({error: err.message});
});

//listen for requests
app.listen(process.env.port || 4000,() => {
    console.log('now listening for requests');
});

Однако, когда я попытался использовать POSTMAN для тестирования API, я обнаружил, что даже если я не задал какой-то параметр, система все равно вернет успешное сообщение. введите описание изображения здесь

Могу ли я узнать, есть ли что-то неправильное или отсутствующее в моем коде, из-за которого ключевое слово require не работает? Большое вам спасибо!

Hon

1 Ответ

0 голосов
/ 02 августа 2020

Замените require ключевым словом required в вашей схеме

const NinjaSchema = new Schema({
    name:{
        type: String,
        required: [true,'Name field is required']
    },
    rank:{
        type: String,
        required: [true,'This field is required']
    },
    available:{
        type: Boolean,
        default: false,
        required: [true,'This field is required']
    }
    //add in geo loction
});

См. this для справки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...