MongoDB Node check if objectid is valid

前端 未结 8 2421
甜味超标
甜味超标 2020-11-28 11:26

How can I check whether an ObjectID is valid using Node\'s driver

I tried :

var BSON = mongo.BSONPure;
console.log(\"Validity: \"  + BSON.ObjectID.is         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 12:30

    Below is my model where I am trying to validate subject id that is of type objectId data using JOI (Joi.objectId().required()):

    const Joi = require('joi');
    const mongoose = require('mongoose');
    
    const Category = mongoose.model('Category', new mongoose.Schema({
      name: String
    }));
    
    function validateCategory(category) {
      const schema = {
        name: Joi.string().min(5).max(50).required(),
        subject_id: Joi.objectId().required(),
      };
    
      return Joi.validate(category, schema);
    }
    
    exports.Category = Category;
    exports.validate = validateCategory;
    

    It will validate like this if anyone tries to send invalid objectId

    joi-objectid validates that the value is an alphanumeric string of 24 characters in length.

    MongoDB ObjectId validator for Joi.

提交回复
热议问题