Mongoose Casterror:cast to ObjectId failed for value

Source: Internet
Author: User



The restfull routes are as follows:


Router.get ('/:id ', controller.show);


The Mongoes code is as follows:


Exports.show = function(req, res) {
   Notice.findById(req.params.id, function (err, notice) {
     If(err) {
       Res.json({no:0,msg:‘Get failed: ‘+err});
     }else{
       Var result = {no:1};
       Result.obj=notice;
       Res.json(result);
     }
   });
};


Client Access:



Http://192.168.0.165:9000/api/notices/11



The printing results are as follows;


{
"no": 0,
"msg": "Get failed: CastError: Cast to ObjectId failed for value \"11\" at path \"_id\""
} 


Specific reasons for reference:



Http://stackoverflow.com/questions/14940660/whats-mongoose-error-cast-to-objectid-failed-for-value-xxx-at-path-id



Mongoose's method casts the parameter to the type of the model's field so,findByIdid_idIt can properly query for The matching doc. This was an ObjectId"11"-a valid ObjectId so the cast fails.






If the client passes the MONGO Objectid, the above error is not reported. For example, the following access methods:



HTTP://192.168.0.165:9000/API/NOTICES/41224D776A326FB40F000001 will not error.

 
 
{
"no": 1,
"obj": null
}


Under normal circumstances, the ID parameter passed by the client is obtained from the background objectid, but for rigor now do the following:


Exports.show = function(req, res) {
   Var id = req.params.id;

   If (id.match(/^[0-9a-fA-F]{24}$/)) {
     Notice.findById(id, function (err, notice) {
       If(err) {
         Res.json({no:0,msg:‘Get failed: ‘+err});
       }else{
         Var result = {no:1};
         Result.obj=notice;
         Res.json(result);
       }
     });
   }else{
     Res.json({no:0,msg:id+‘no ‘});
   }

};

Mongoose Casterror:cast to ObjectId failed for value


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.