MERN Stack-为什么我的发帖请求在Postman上抛出错误?无法发布目的地

时间:2019-07-12 18:03:11

标签: node.js mongodb express mongoose

我在MERN堆栈上还比较陌生。我有2个名为User和Destination的模型。他们之间有关系。在用户架构中,它具有目标ID的数组,并且目标具有对一个特定用户的引用。我尝试发布的目的地具有一个名称,我使用express validate来验证其存在,但是当我尝试在Postman上发布请求时,出现

错误
{
    "errors": [
        {
            "msg": "name of destination is required",
            "param": "name",
            "location": "body"
        }
    ]
}

我尝试删除代码的验证方面,但是随后出现

错误
  

目标验证失败:名称:路径name是必需的。

代码在下面。感谢提供的任何帮助。 //User.js

const mongoose = require('mongoose');
const Destination = require('./Destination.js')


const UserSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    destinations: [{type: mongoose.Schema.Types.ObjectId, ref: 'destination'}]

})


module.exports = mongoose.model('user', UserSchema);

users.js

const express = require('express');
const router = express.Router();
const {check, validationResult} = require("express-validator")
const bcrypt = require("bcryptjs")
const jwt = require('jsonwebtoken')

const User = require("../models/User.js")
const config = require("config")
const auth = require('../middleware/auth')

const Destination = require('../models/Destination');




// @route GET api/users/destination
// @desc get all destinations for a particular user
// @access private
router.get('/:id/alldestinations', auth, async (req, res) => {
    try { //placeholder 


    } catch (err) { //placeholder

    }
})





// @route   GET     api/users
// @desc    get all users from database
// @access      Private
router.get('/', auth,  async (req, res) => {
    try {
        const users = await User.find({})
        res.json(users)

    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error')
    }
});



// @route   POST    api/users
// @desc    Register a user
// @access      Public


//handling post request with validations
//makes sure that the name, email and password are present

router.post('/', [
    check('name', 'name is required').not().isEmpty(),
    check('username', 'please enter a username').not().isEmpty(),
    check('email', 'Please enter a valid email').isEmail(),
    check('password', 'please enter a password with 6 or more characters').isLength({min: 6})


], async (req, res) => {


    const errors = validationResult(req);
    if(!errors.isEmpty()) {
        return res.status(400).json({errors: errors.array() });
    }

    const {name, email, username,  password} = req.body;

    try {
        let user = await User.findOne({ email});

        if(user) {
            return res.status(400).json({message: "User already exists"});
        }

        user = new User({
            name,
            username,
            email,
            password
        })

        const salt = await bcrypt.genSalt(10)

        user.password = await bcrypt.hash(password, salt);

        await user.save();

        const payload = {
            user: {
                id: user.id
            }
        }

        jwt.sign(payload, config.get('jwtSecret'), {
            expiresIn: 360000
        }, (err, token) => {
            if(err) throw err;
            res.json({token});
        } )

    } catch (err) {
        console.error(err.message);
        res.status(500).send("server error")

    }


}
);






module.exports = router;

Destination.js

const mongoose = require('mongoose');
const User = require('./User.js')

//geolocation schema
const geoLocation = mongoose.Schema({
    type: {
        type: String,
        default: "Point"
    },
    coordinates: {
        type: [Number],
        index: "2dsphere"
    }
})


const DestinationSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    geometry: geoLocation,
    user: {
        type: mongoose.Schema.Types.ObjectId, ref: 'user'
    }
});

module.exports = mongoose.model('destination', DestinationSchema)

destinations.js

const express = require('express');
const router = express.Router();

const auth = require('../middleware/auth')
const {check, validationResult} = require('express-validator');

const User = require('../models/User');
const Destination = require('../models/Destination');


// @route       GET a api/destinations
// @desc        get all destinations for a particular user
// @access      Private
router.get('/', auth , async (req, res) => {
    try {

        //finds the destination that belongs to a particular user by finding the associated ID
        const destination = await Destination.find({ user: req.user.id })
        res.json(destination)

    } catch(err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
})


// @route   POST    api/destinations
// @desc    Save a destination
// @access      Private
router.post('/', [auth, [
    check('name', 'name of destination is required').not().isEmpty()
    ]
] , async  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({errors: errors.array() });

    }

    const {name, geometry} = req.body

    try{
        const newDestination = new Destination({
            name,
            geometry,
            user: req.user.id
        });

        const destination = await newDestination.save();

    } catch(err) {
        console.error(err.message)
        res.status(500).send('Server Error')

    }
});

process.on('unhandledRejection', (reason, promise) => {
    console.log('Unhandled Rejection at:', reason.stack || reason)
    // Recommended: send the information to sentry.io
    // or whatever crash reporting service you use
  })



    // @route   DELETE  api/destinations/:id
    // @desc    Save a destination
    // @access      Private
    router.delete('/:id', (req, res) => {
        res.send('Delete a destination')
    });

    module.exports = router;

0 个答案:

没有答案