How To Check MongoDB ID Valid Or Not

As you must aware about the object ID in mongo database or MongoDB is 24 characters long so for check is it valid id or not there is no direct validation method in validations package such as node-input-validator.

MongoDB - Education Funda
MongoDB - Education Funda

So for checking entered id is valid or not we can us below tech-tics:

Approach 1 - Simple JS Validation

var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")

checkForHexRegExp.test("i am a string") // false
checkForHexRegExp.test("5e63c3a5e4232e4cd0074ac2") // true

Approach 2 - With Mongo DB Method (Best Way)

var ObjectID = require("mongodb").ObjectID

ObjectID.isValid("i am a string") // false
ObjectID.isValid("5e63c3a5e4232e4cd0274332") // true


With Node Input Validator You Can Use Below Method:

const id_exists = "required|string|minLength:24|maxLength:24|idExists"

 
const validator = require("node-input-validator")
const mongoose = require('mongoose')
 
/**
* to check given id exists in given table
* additional column checks can be passed in pairs
* e.g exists:table_name,primary_id,col1,value1,col2,value2 and so on
* col-value must be in pairs
*/
validator.extend("idExists", async function({value, args}){
console.log("ValidatorsIndex => idExists", value, args)
var ObjectID = require("mongodb").ObjectId
if(ObjectID.isValid(value) === true){
let condition = {},
schema = args[0]
condition['_id'] = value

let alreadyExists = await mongoose.model(schema).findOne(condition)

return (alreadyExists) ? true : false
}else{
return false
}
})

 

classIdExists: `${id_exists}:Class`,

 

Thanks for reading this blog,I hope it will helpful for you.

Comments

Popular posts from this blog

JavaScript Logical Output Based Interview Questions

Create and Deploy AWS SAM Application

Deploy Angular Build With Express JS Project