Home > Mobile >  "err": "Cannot read property 'id' of undefined" in POSTMAN
"err": "Cannot read property 'id' of undefined" in POSTMAN

Time:03-25

I am practicing with API's and building out controller functions to create, index, show, update and delete puppies from the database. In order to check that all my routes are working correctly I am using Postman and so far so good, except for my show function. The show controller function is supposed to find a single puppy by the id.

I am trying to send a GET request with a specific id and I am supposed to receive the object I CREATEd earlier but instead I get{"err": "Cannot read property 'id' of undefined"}

can anyone help me? why is it not accepting the id?

Server.js

import('./config/database.js')


app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(
express.static(
path.join(path.dirname(fileURLToPath(import.meta.url)), 'public')
)
)

// mounted routers
app.use('/api/puppies', puppiesRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
// render the error page
res.status(err.status || 500).json({"err": err.message})
})

export {
app
}

database.js

import mongoose from 'mongoose'

const db = mongoose.connection

mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
// useCreateIndex: true,
useUnifiedTopology: true,
// useFindAndModify: false,
})`

db.on('connected', function() {
console.log(Connected to MongoDB ${db.name} at ${db.host}:${db.port})
})

routes:

import { Router } from 'express'
const router = Router()
import * as puppiesCtrl from '../controllers/puppies.js'

router.get('/', puppiesCtrl.index)
router.get('/:id', puppiesCtrl.show)
router.post('/', puppiesCtrl.create)

export {
router
}

controllers:

import { Puppy } from '../models/puppy.js'

export{
create,
index,
show,
}

function create(req, res){
Puppy.create(req.body)
.then(puppy => res.status(201).json(puppy))
.catch(err => {
console.log(err)
res.status(500).json(err)
})
}

function index(req, res){
Puppy.find({})
.then(puppies => res.status(200).json(puppies))
.catch(err => {
console.log(err)
res.status(500).json(err)
})
}

function show(req,res){
Puppy.findById(req.parmas.id)
.then(puppy => res.status(200).json(puppy))
.catch(err => {
console.log(err)
res.status(500).json(err)
})
}

CodePudding user response:

It is because of misspelling the argument to Puppy.findById(), you entered req.parmas.id and it should be req.params.id.

  • Related