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