Node/Express + MongoでAPIを作成する。IDが見つからない場合、mongoose findByIdがエラーを返す理由
私はいくつかのユニットテストを書いていると私は_id=1
ため/profile/1
を取得しようとする場合、私は観察私はこのエラーを得た(私は_id=1
を持つことはできませんので、モンゴがデフォルトでIDを入れてみましょう)
MongooseError: Cast to ObjectId failed for value "1" at path "_id"
私は空のオブジェクトUserを持つと思った。
function getProfile(req, res) {
const userId = req.params.userId
User.findById(userId, "-password", (err, user) => {
if (err) {
console.log(err);
res.status(400)
res.json({
success: false,
err
})
res.end()
return
}
if (!user) {
res.status(404)
res.json({
success: false,
message: `Cannot find an User with the userId: ${userId}`
})
res.end()
return
}
res.json({
success: true,
user: user
})
res.end()
return
})
}
私のテスト:
describe('Test /profile route',() => {
it('shouldn\'t find Joe Doe\'s profile with a wrong ID\n', (done) => {
chai.request(server)
.get(`/profile/1`)
.end((err, res) => {
expect(res).to.have.status(404)
done()
})
})
私はエラー404(第2の場合を持っているだろうと思った、と私はそれが正しいコード・エラーではありません知っている、私はどこ私のテストを参照するためだけの簡単な方法行く)しかし、私は400を持っている - >エラーが戻ってくることを意味します。
私はmongooseのドキュメントを読んでいますが、私は実際には別の方法で戻り値を説明していません。
? – brandonscript
問題は、それがIntのような型のようですが、ObjectIdを期待しているように見えます。 TypeScriptを使用していますか? – brandonscript
テストコードを残して忘れてしまいました。そして、私はTypeScriptを使用していません。 (私はそれについて聞きましたが、私はまだそれについて正直であることを読んでいませんでした) – Ragnar