简体   繁体   中英

Express Server routing issue

I'm trying to add a new route to fetch a user by id but my error handling is not working correctly. Here is the code for that route.

const express = require('express');

require('./db/mongoose');
const User = require('./models/user');
const Task = require('./models/task');

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

app.use(express.json());

//  ***removed code for brevity
// Route for fetching user by id

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

    User.findById(_id)
        .then(user => {
            //console.log(user)
            if (!user) {
                return res.status(404).send();
            }
            res.send(user);
        })
        .catch(e => {
            res.status(500).send();
        });
});

So if I test the route on Postman and I enter the correct user id from the database I get that user sent back, which is the the correct response. But if I enter an incorrect user id I get the 500 error code response instead of the 404 error code. The if (!user) statement is getting skipped and I can't figure out why. Any thoughts as to what I am missing?

Running this thru my own personal mongoose/express-using project, I get the following error:

 UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "12345" at path "_id" for model "User"

That basically means Mongoose is expecting its own specific object type, an "ObjectId". This is a bit of a pain, since normally if you're using .findOne({_id:something), you can just use a string. If we do:

User.findById(mongoose.Types.ObjectId(_id))

it should work. Note that if you use an invalid id (like I obviously did here, it'll still error out. For that reason, I'd use the standard NodeJS format for callbacky stuff:

.then((err,result)=>{
   //other stuff
});

In general, the .catch() block should only happen if obviously Mongoose and your router can't handle it.

EDIT: Also, for others info, Mongoose.model.findById is a built-in convenience method, and should basically do exactly what it says on the tin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM