当找不到结果时,猫鼬的findById不会返回null

时间:2020-03-14 10:57:57

标签: node.js mongodb mongoose

当我提供不存在的id时,if语句应该返回404错误,但不会。插入它会发送500错误

const express = require("express");
require("./db/mongoose");
const User = require("./models/user");


const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());


app.get("/users/:id", (req, res) => {
  const _id = req.params.id;

  User.findById(_id)
    .then(user => {
      if (!user) {
        return res.status(404).send();
      }

      res.send(user);
    })
    .catch(e => {
      res.status(500).send();
    });
});

app.listen(port, () => {
  console.log("Server is up on port " + port);
});

1 个答案:

答案 0 :(得分:2)

尝试在查询之前检查有效的ObjectId,

const mongoose = require("mongoose")

app.get("/users/:id", (req, res) => {
  const _id = req.params.id;
  const isValidId = mongoose.Types.ObjectId.isValid(_id)

  if (!isValidId) return res.status(400).send("id is not valid")

  ... //continue your code here

})