1

Im using ExpressJS and MongooseJS:

exports.show = function(req, res) {
    var id = req.params.id;
    Subject.findById(id, function(err, subject) {
        if ( err ) {
            return res.json(err);
        }

        res.render('subject/view', {subject: subject});
    });
};

When id is invalid, users got:

{
  "message": "Cast to ObjectId failed for value \"some_id\" at path \"_id\"",
  "name": "CastError",
  "type": "ObjectId",
  "value": "some_id",
  "path": "_id"
}

How to check id is valid before passing it to findById?

Thanks

JR Galia
  • 17,229
  • 19
  • 92
  • 144
  • Or this one using JavaScript: http://stackoverflow.com/questions/11985228/mongodb-node-check-if-objectid-is-valid – WiredPrairie Aug 26 '13 at 12:11
  • Inspired me to write a simple blog post about Mongoose plugins: http://www.wiredprairie.us/blog/index.php/archives/1928 – WiredPrairie Aug 26 '13 at 12:35

0 Answers0