我有以下回圈模式
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
我們將上述模型匯入到路由檔案中,如下所示
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
這是在 server.js 中匯入的
const cyclesRouter=require('./routes/cycles')
app.use('/cycles', cyclesRouter)
然后我們運行服務器并嘗試在郵遞員中獲取周期請求,我們得到這樣的結果
但是當我們嘗試使用下面的 id 引數來獲取特定的回圈時,我們會得到如下的 404 錯誤
mongodb CLI 具有以下結構
任何幫助將不勝感激
uj5u.com熱心網友回復:
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))
uj5u.com熱心網友回復:
似乎錯誤在路線中,而不是基于郵遞員回應的查詢。
嘗試洗掉額外的“.route()”,除非您鏈接 HTTP 方法,否則這是不必要的。
router.get('/:id', (req,res)=>{
Cycle.findById(req.params.id)
.then(cycle=>res.json(cycle))
.catch(err=>res.status(400).json('Error:' err))
})
或者進行一些額外的錯誤檢查...
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))
})
uj5u.com熱心網友回復:
該問題的正確答案是,將獲取 id 請求的代碼更改為發布、洗掉并嘗試通過郵遞員點擊它,嘗試多次并給它 1 小時。輸入和之前一樣的代碼
router.route('/:id').get((req,res)=>{
Cycle.findById(req.params.id)
.then(cycle=>res.json(cycle))
.catch(err=>res.status(400).json('Error:' err) )
})
洗掉資料庫中的所有專案并創建新專案/添加專案(從前端執行此操作),然后嘗試從前端訪問單個周期的 api url,然后再次檢查 Postman,這些嘗試之一應該有效,并且它為我作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/522316.html