BT101
BT101

Reputation: 3836

Should I validate get parameter with mongoose

In my routing I have get request:

router.get('/getOne', auth(), mapController.getOne);

I'm passing id parameter in url and doing mongo query with mongoose in mapController like this:

exports.getOne = async(req, res, next) => {
    try {
        const mapData = await Map.findById(req.query.id);
        res.json(mapData);
    } catch (e) {
        return next(e);
    }
};

previously I was working with PHP where we were escaping parameters to avoid sql injection. Here I'm not doing anything similiar I just pass req.query.id straight to findById method. Is everything okey with above code when it comes to security?

Upvotes: 1

Views: 344

Answers (1)

Akrion
Akrion

Reputation: 18525

In this case Mongoose would detect that you are passing a string and internally would try to convert it to mongodb ObjectId. If that fails it would not run the query. The error you would get is:

UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "VALUE HERE" at path "_id" for model "Map"

So as you see you either pass an actual mongoDb ObjectId or a valid string which can be casted to one. Anything else would produce a CastError by Mongoose.

Upvotes: 1

Related Questions