Home > Net >  findbyID is not returning individual item in db, 404 not found error , mongodb, mongoose
findbyID is not returning individual item in db, 404 not found error , mongodb, mongoose

Time:10-28

I have the following Cycle Schema

const mongoose=require('mongoose')

const Schema = mongoose.Schema;

const cycleSchema= new Schema({
     
     startDate:{type:Date,required:true},
     endDate:{type:Date,required:true},
     users:[
       {
        firstName:String,
        lastName:String,
        goals:[{
            mainGoal:String,
            progress:{
                type:Number,
                default:0
            },
            subTasks: [{
                task:String,
                done:Boolean
            }]
        }]
       }
     ]    
},{
    timestamps:true
})

const Cycle= mongoose.model('Cycle', cycleSchema)

module.exports = Cycle

And we import the above model to routes file as below

const router = require('express').Router()
const Cycle = require('../models/cycle.model')


router.route('/').get((req,res)=>{
    console.log("getting cycles ..")
    Cycle.find()
    .then(cycle=>res.json(cycle))
    .catch(err=>res.status(400).json("Error "  err))
})


router.route('/add').post((req,res)=>{
 
const startDate= Date.parse ( req.body.startDate) 
const endDate=  Date.parse ( req.body.endDate) 
 

const users=req.body.users


const newCycle=new Cycle({
    startDate,endDate,users
})


router.route('/:id').get((req,res)=>{
    
    Cycle.findById(req.params.id)
    .then(cycle=>res.json(cycle))
    .catch(err=>res.status(400).json('Error:'   err))
}) 

module.exports = router

And this is imported in server.js


const cyclesRouter=require('./routes/cycles')


app.use('/cycles', cyclesRouter)

then we run the server and try the Get cycles request in postman we get something like this

enter image description here

But when we try to get that specific cycle by using the id parameter as below , we get the 404 error as below enter image description here

The mongodb CLI has the following structure enter image description here Any help here would be appreciated

CodePudding user response:

var ObjectId = require('mongodb').ObjectID;


Cycle.findById(new ObjectId(req.params._id))
    .then(cycle=>res.json(cycle))
    .catch(err=>res.status(400).json('Error:'   err))

CodePudding user response:

Seems like the error is in the route and not the query based on the response from Postman.

Try removing the additional '.route()' which is not necessary unless you are chaining HTTP methods.

router.get('/:id', (req,res)=>{
    
    Cycle.findById(req.params.id)
    .then(cycle=>res.json(cycle))
    .catch(err=>res.status(400).json('Error:'   err))
})

Or with some additional error checking...

router.get('/:id', (req, res, next) => {

  Cycle.findById(req.params.id)
    .then(cycle => {
      if (!cycle) {
        return next(console.log(`Cycle with id ${req.params.id} not found`))
      } else {
        return res.json(cycle)
      }
    })
    .catch(err => res.status(400).json('Error:'   err))
})

CodePudding user response:

The correct answer to the question would be , Change the code for get id request to post, delete and try to hit it through postman, Try multiple times and give it 1hr. Put the same code in as before

router.route('/:id').get((req,res)=>{
    
    Cycle.findById(req.params.id)
    .then(cycle=>res.json(cycle))
    .catch(err=>res.status(400).json('Error:'   err) )
}) 

Delete all items in the database and create new items/ add items (do this from the front-end ), then try to access the api url for individual cycle from frontend, then check Postman again, one of these attempts should work, and it worked for me.

enter image description here

  • Related