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
But when we try to get that specific cycle by using the id parameter as below , we get the 404 error as below
The mongodb CLI has the following structure
Any help here would be appreciated
3
Answers
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
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.
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.
Or with some additional error checking…