MERN-TypeError:无法读取未定义的属性“ id”

时间:2019-11-10 05:48:23

标签: node.js mongodb express mongoose mern

我做了很多研究,尝试了不同的方法,但是我似乎可以解决某些POST请求。

GET请求和POST请求添加了练习,但POST请求删除或更新了练习。

我的假设是,exercises.js文件中的express无法识别某些响应,因为只要更新或删除路由中的 Exercise.findById(res.params.id)失败,它就会失败。叫。

任何帮助将不胜感激。

server.js

const express = require('express') // Express web framework
const cors = require('cors') // Cross-origin resource sharing (CORS) -> Connects Express
const mongoose = require('mongoose') // Mongoose will connect us to the mongoDB database

const exercisesRouter = require('./routes/exercises')
const usersRouter = require('./routes/users')

require('dotenv').config() // configure environment variables in .env file

// to create the Express server
const app = express()
const port = process.env.PORT || 5000 // 5000 Port

// Middleware 
app.use(cors()) // CORS middleware
app.use(express.json()) // Express middleware to allow us to parse JSON

// MongoDB Connection process
const uri = process.env.ATLAS_URI // MongoDB database URI connection string form mongoDB Atlas -- ATLAS_URI will be stored in .env file
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }) // start connection to db
const connection = mongoose.connection
connection.once('open', () => {
    console.log("MongoDB database connection established successfully")
})

// Routing to respective pages
app.use('/exercises', exercisesRouter) // routes to /exercises page
app.use('/users', usersRouter)// routes to /users page

// Start the server
app.listen(port, () => {
    console.log(`Server is running on port: ${port}`)
})

exercises.model.js

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

const exerciseSchema = new Schema({
    username: { type: String, required: true },
    description: { type: String, required: true}, 
    duration: { type: Number, required: true},
    date: { type: Date, required: true} 
}, {
    timestamps: true,
})

const Exercise = mongoose.model('Exercise', exerciseSchema)

module.exports = Exercise

exercises.js

const router = require('express').Router() // Creating route for Exercises
let Exercise = require('../models/exercises.model') // Mongoose model

// Handles incoming HTTP GET requests for /exercises URL
router.route('/').get((req, res) => {
    Exercise.find()
        .then(exercises => res.json(exercises))
        .catch(err => res.status(400).json('Error: ' + err))
})

/*** Handles incoming HTTP POST requests ***/

// Create new exercise
router.route('/add').post((req, res) => {
    const username = req.body.username
    const description = req.body.description
    const duration = Number(req.body.duration)
    const date = Date.parse(req.body.date)

    const newExercise = new Exercise({
        username,
        description,
        duration,
        date
    })

    newExercise.save()
    .then(() => res.json('Exercise added !'))
    .catch(err => res.status(400).json('Error = ' + err))
})

// Get exercise by ID
router.route('/:id').get((req, res) => {
    Exercise.findById(req.params.id)
        .then(exercises => res.json(exercises))
        .catch(err => res.status(400).json('Error: ' + err))
})

// Delete exercise
router.route('/:id').delete((res, req) => {
    Exercise.findByIdAndDelete(req.params.id)
    .then(() => res.json('Exercise deleted'))
    .catch(err => res.status(400).json('Error: ' + err))
})

// Update exercise
router.route('/update/:id').post((res, req) => {
    Exercise.findById(req.params.id)
    .then(exercises => {
        exercises.username = req.body.username
        exercises.description = req.body.description
        exercises.duration = Number(req.body.duration)
        exercises.date = Date.parse(req.body.date)

        exercises.save()
            .then(() => res.json('Exercise updated!'))
            .catch(err => res.status(400).json('Error: ' + err))
    })
    .catch(err => res.status(400).json('Error: ' + err))
})


module.exports = router

nodemon服务器输出

[nodemon] starting `node server.js` Server is running on port: 5000 MongoDB database connection established successfully TypeError: Cannot read property 'id' of undefined at C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\routes\exercises.js:48:34 at Layer.handle [as handle_request] (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\layer.js:95:5) at C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:281:22 at param (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:354:14) at param (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:365:14) at Function.process_params (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:410:3) at next (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:275:10) at Function.handle (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:47:12) at Layer.handle [as handle_request] (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:317:13) at C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\sambaetleuk\Projects\mern-fitness-tracker\backend\node_modules\express\lib\router\index.js:335:12)

2 个答案:

答案 0 :(得分:2)

我能想到的一个解决方案是您的回调函数中的->(req,res),因为通常按此顺序进行。

答案 1 :(得分:0)

在这种情况下,您将获得未定义的ID值,请使用req.body.id

exercises.js

router.route('/update/:id').post((res, req) => {
Exercise.findById(req.body.id).then().catch()