khaoulaelko
khaoulaelko

Reputation: 23

Mongoose findById won't return null when no result found

when I provide a none existing id the if statement is supposed to return an 404 error but it doesn't. Insted it sends an 500 error

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);
});

Upvotes: 2

Views: 924

Answers (2)

Sheraz Nabi Mirza
Sheraz Nabi Mirza

Reputation: 1

You need to input either 12 or 24 byte input for it to be a valid ID and return a 404 error, otherwise it will return a 500 error.

Upvotes: 0

Nilesh Singh
Nilesh Singh

Reputation: 1750

Try checking for a valid ObjectId before querying,

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

})

Upvotes: 2

Related Questions