我提出了一個獲取請求,但我有一個關于 _id 引數的錯誤,它無法讀取
app.get('/users/:id', (res, req) => { const _id = req.params.id
if(_id.length != 24) {
res.status(404).send(`id length must be do not less than 24 digit`)
} else {
User.findById(_id).then((user) => {
if (!user) {
res.status(404).send(`the user id is not found `)
}
res.status(200).send(user)
}).catch((e) => {
res.status(500).send(e)
})
}
})
uj5u.com熱心網友回復:
試試: User.findById({_id:_id}) 告訴我它是否有效
uj5u.com熱心網友回復:
const id = req.params.id;
if(id.length != 24) {
res.status(404).send(`id length sholud be 24 digit`)
} else {
User.findById({_id:id}).then((user) => {
if (!user) {
res.status(404).send(`the user id is not found `)
}
res.status(200).send(user)
}).catch((e) => {
res.status(500).send(e)
})
}
})
uj5u.com熱心網友回復:
最后,我明白了。關于貓鼬中的 id 必須將其轉換為字串,然后長度必須等于 12 個位元組。
app.get('/users/:id', (req,res) => {
const _id = req.params.id
if(_id.toString().length!= 12) {
User.findById(_id).then((user) =>
if(!user) {
return res.status(404).send('unable to find user')
}
return res.status(200).send(user)
}).catch((e) => {
return res.status(500).send(e)
})
} else {
res.status(400).send('bad objectID')
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/476006.html
下一篇:獲取最近X天的記錄
