简体   繁体   中英

Mongoose findById function returning weird response

I am creating an Rest API using node.js,express and mongoDb. I had an endpoint for user registration which simply adds user details into the database.

User Schema looks like this:-

const userSchema= new mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    referenceId:{
        type:String,
        default: ''
    },
    password:{
        type:String,
        required:true
    }
})

User registration part is working fine as expected.

I also need an endpoint which takes user id and returns the user details in json format. This is what i have coded so far.

/*
    This endpoint returns the data of a single user with given user id
*/
router.get('/:id',async(req,res)=>{
    //This function will return the registered user with given id.
    try{
        const user=await User.findById(req.params.id);
        if(!user){
            res.send("Could not found");
        }
        res.json(user);
    }catch(err){
        res.send(err);
    }
})

This part is also working fine if the user exists with the given id. If user does not exists i need to return an custom error message. But in that case below response is returned.

{
    "stringValue": "\"5eecac810ea3711230b58a9\"",
    "kind": "ObjectId",
    "value": "5eecac810ea3711230b58a9",
    "path": "_id",
    "reason": {}
}  

So my question is what is this weird response and how could i handle user not found case.

BTW 5eecac810ea3711230b58a9 is the userid i searched for which does not exists.

EDIT:-

After a little bit of debugging i found that the program control transferred to the catch block and the response is generated in the catch block instead of try block.

/*
    This endpoint returns the data of a single user with given user id
*/
router.get('/:id',async(req,res)=>{
    //This function will return the registered user with given id.
    console.log('Here');
    try{
        const user=await User.findById(req.params.id);
        console.log(user._id);
        res.json(user);
    }catch(err){
        //This works when user is not found
        res.send("Could Not found");
    }
})

Not finding any records isn't an error condition. To check if the user doesn't exist you could check if a specific field exists rather than if(!user) .

Something like

if(!user.id){
   res.send("Could not found");
}

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