question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

feat: add `@IsMongoIdObject` decorator

See original GitHub issue

Description

  1. @IsMongoId() just checks if it is a string (see below, taken from your code base) where you could have used ObjectId.isValid() from the mongodb or bson repo.
  2. Is this repo still maintained?
export function isMongoId(value: unknown): boolean {
    return typeof value === "string" && validator.isMongoId(value);
}

Reproduction

Create a Mongo Id with new ObjectId() and you’ll get an error when validating. Can’t provide any sandbox. Tried Stackblitz and CodeSandbox but they can’t get bson or mongodb running. So you have try yourself in you IDE:

import { IsMongoId, validateSync } from 'class-validator'
import { ObjectId } from 'mongodb'

class A {
  @IsMongoId()
  _id = new ObjectId()
}

console.log(validateSync(new A()))

Environment

  • nodejs: 14.4
  • browser: not relevant
  • framework/library: nothing

class-validator version: 0.12.2

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

7reactions
Kiliandecacommented, Jun 17, 2020

Hello, I think this is the intended behaviour, most of the decorator are under the “String validation decorators” section in the readme.

Internally this library use validator.js to perform validation and as you can see it’s “A library of string validators and sanitizers”.

It’s wrong to say that it just checks if it is a string because as you can see from the code you quote we also do the validator.js check. && validator.isMongoId(value);. You can find the underlying code at this url. It check if it’s an hexadecimal string of lenght 24. If this is not the right behavior you can open an issue upstream but using mongodb or bson to do object validation seem out of scope since it’s a string validation library.

However you can probably do what you want with class-validator using custom validation decorator (link to the doc)

I did not test but It would look something along the line of:

import {registerDecorator, ValidationOptions, ValidationArguments} from "class-validator";
import { ObjectId } from "bson"

export function IsMongoIdObject(validationOptions?: ValidationOptions) {
   return function (object: Object, propertyName: string) {
        registerDecorator({
            name: "IsMongoIdObject",
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return ObjectId.isValid(value)
                }
            }
        });
   };
}

then use it as:

class A {
  @IsMongoIdObject()
  _id = new ObjectId()
}
1reaction
desmapcommented, Jul 2, 2020

Thanks. I saw that I can create a custom validator, so this should do the job for now.

I think this is the intended behaviour, most of the decorator are under the “String validation decorators” section in the readme.

IDK, following your logic (it’s in a ‘string’ subfolder + the upstream repo isn’t doing more) you might be right. But from a user’s view who just ESM-imports { IsMongoId } without reading the sources or folder structures too much, he/she assumes and expects it’s the original validator function from the bson lib. So, this might be intended from your side but it’s still misleading.

Read more comments on GitHub >

github_iconTop Results From Across the Web

class-validator-mongo-object-id - npm
class-validator-mongo-object-id. TypeScript icon, indicating that this package has built-in type declarations.
Read more >
How to validate if a Param string is a MongoId in Nestjs ...
The answer to this is to use a custom Validation pipe: Create the pipe and export it: import { ArgumentMetadata, BadRequestException ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found