如果找不到 ID,为什么猫鼬 findById 会返回错误

Rag*_*nar 6 mongoose mongodb node.js

使用 Node/Express + Mongo 制作 API。

我正在写一些单元测试和我观察,如果我尝试获得/profile/1_id=1(我让默认蒙戈把ID,所以我不能有_id=1)我得到这个错误

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
  })
}
Run Code Online (Sandbox Code Playgroud)

我的测试:

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()
      })
    })
Run Code Online (Sandbox Code Playgroud)

我以为我会遇到错误 404(第二个如果,并且我知道这不是正确的代码错误,只是让我快速查看测试进行的方式)但是我得到了 400 -> 意味着返回错误。

我阅读了猫鼬文档,但我真的没有看到他们用不同的方法解释了返回值。

Mar*_*rkB 6

问题是“1”不是有效的猫鼬对象 ID。因此它试图比较不同的类型。

尝试将其转换为对象 id,如下所示:

userId = mongoose.Types.ObjectId(userId)
Run Code Online (Sandbox Code Playgroud)

然后运行您的查询

User.findById(userId, "-password", (err, user) => { .... });
Run Code Online (Sandbox Code Playgroud)