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

Posted

技术标签:

【中文标题】MERN - TypeError:无法读取未定义的属性“id”【英文标题】:MERN - TypeError: Cannot read property 'id' of undefined 【发布时间】:2020-03-06 05:43:26 【问题描述】:

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

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

我的假设是,某些响应不会被exists.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)

【问题讨论】:

【参考方案1】:

你的问题是这样的

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

你在(res, req)之间交换应该是(req, res)

【讨论】:

【参考方案2】:

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

【讨论】:

【参考方案3】:

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

exercises.js

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

【讨论】:

以上是关于MERN - TypeError:无法读取未定义的属性“id”的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法在nodejs中读取未定义的属性“email”

TypeError:无法在身份验证时读取未定义的属性“jwtoken”

如何使用自定义错误消息捕获“TypeError:无法读取未定义的属性(读取'0')”?

TypeError:无法读取未定义的属性(读取“名称”)

TypeError:无法读取未定义的属性(读取“问题”)

TypeError:无法读取未定义的属性“findAll”(expressjs)