MongoDB with NodeJS: Validate ObjectID
MongoDB ObjectID
Create a new ObjectID and query using findOne()
To query a document by its _id
field in the database we can use a simple call od the findOne()
method on the database collection object. To query by the exact id we have to convert it to an objectID first. You can see a simple example below:
const sessionIdObject = new ObjectId(request.body.sessionId);
if (sessionIdObject) {
const result = await database.collection('sessions').findOne({ _id: sessionIdObject });
if (result) {
response.status(200).send({ sessionId: result });
} else {
response.status(400).send({ error: 'SESSION_NOT_FOUND' });
}
} else {
response.status(400).send({ error: 'SESSION_ID_INVALID' });
}
The new ObjectID(id: string)
constructor requires a valid object id string. This means either a string of 12 bytes or a string of 24 hex charaters. If the string does not fulfil this requiremewnts you will get the following error:
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters at new ObjectID
Validate any string to be a valid ObjectID
That means we have to check the given string to be a potential ObjectID. Using one of the both approaches below prevent unexpected errors while querying data using the _id
field.
A simple but not fail-safe attempt is to use a regex pattern as shown below:
var validationRegex = new RegExp("^[0-9a-fA-F]{24}$")
validationRegex.test("very invalid") // false
validationRegex.test("5e63c3a5e4232e4cd0274ac2") // true
A more foolproof way is to use the isValid(potentialId: string)
given by the mongodb library. The method is documented at GitHub and can be used freely.
var ObjectID = require("mongodb").ObjectID
ObjectID.isValid("very invalid") // false
ObjectID.isValid("5e63c3a5e4232e4cd0274ac2") // true