Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate for ObjectID

Using Joi schema validation, is it possible to validate against MongoDB ObjectID's?

Something like this could be great:

_id: Joi.ObjectId().required().error(errorParser),
like image 373
Raz Buchnik Avatar asked Aug 26 '19 13:08

Raz Buchnik


People also ask

What is a valid ObjectId?

ObjectId values are 12 bytes in length, consisting of: a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch. a 5-byte random value generated once per process. This random value is unique to the machine and process.

Does Mongoose actually validate the existence of an object ID?

No, an ObjectId field that's defined in your schema as a reference to another collection is not checked as existing in the referenced collection on a save.

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

What is the datatype for ObjectId?

Binary JSON (BSON)

What is objectId validator for Joi?

joi-objectid validates that the value is an alphanumeric string of 24 characters in length. MongoDB ObjectId validator for Joi. new RegExp ("^ [0-9a-fA-F] {23}$").test ("5e79d319ab5bfb2a9ea4239")

How to validate a string for correct MongoDB ID?

Mongoose & MongoDB provide a very useful function in ObjectId i.e. ObjectId.isValid (“some_id”) to validate a string for correct MongoDB ID. ObjectId can be imported from native mongodb as well as mongoose package. const ObjectId = require ('mongodb').ObjectId; or const mongodb, {ObjectId} = require ('mongodb');

What is object_ID in SQL Server?

OBJECT ID (Transact-SQL) Returns the database object identification number of a schema-scoped object. Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view.

Why is my objectId not valid in MongoDB?

"zzzzzzzzzzzz" is not valid ObjectId. For example Mongo shell listiong (mongodb version - 3.0.2): Sorry, something went wrong. Because the mongodb shell's ObjectId constructor is written such that it only accepts hex strings. It's a restriction in the mongo shell for convenience, not with the BSON type ObjectId.


3 Answers

I find that if I do

Joi.object({
  id: Joi.string().hex().length(24)
})

it works without installing any external library or using RegEx

The hex makes sure the string contains only hexadecimal characters and the length makes sure that it is a string of exactly 24 characters

like image 83
orimdominic Avatar answered Sep 19 '22 02:09

orimdominic


const Joi = require('@hapi/joi')
Joi.objectId = require('joi-objectid')(Joi)
 
const schema = Joi.object({
  id: Joi.objectId(),
  name: Joi.string().max(100),
  date: Joi.date()
})

checkout https://www.npmjs.com/package/joi-objectid

like image 36
prince Arthur Avatar answered Sep 22 '22 02:09

prince Arthur


If you want a TypeScript version of the above library integrated with Express without installing anything:

import Joi from '@hapi/joi';
import { createValidator } from 'express-joi-validation';

export const JoiObjectId = (message = 'valid id') => Joi.string().regex(/^[0-9a-fA-F]{24}$/, message)

const validator = createValidator({
    passError: true,
});

const params = Joi.object({
    id: JoiObjectId().required(),
});

router.get<{ id: string }>(
    '/:id',
    validator.params(params),
    (req, res, next) => { 
       const { id } = req.params; // id has string type
       .... 
    }
);
like image 37
Alecu Marian Alexandru Avatar answered Sep 18 '22 02:09

Alecu Marian Alexandru