Can I determine if a string is a MongoDB ObjectID?

前端 未结 16 717
时光说笑
时光说笑 2020-11-30 00:31

I am doing MongoDB lookups by converting a string to BSON. Is there a way for me to determine if the string I have is a valid ObjectID for Mongo before doing the conversion?

16条回答
  •  悲哀的现实
    2020-11-30 00:59

    Below is a function that both checks with the ObjectId isValid method and whether or not new ObjectId(id) returns the same value. The reason for isValid not being enough alone is described very well by Andy Macleod in the chosen answer.

    const ObjectId = require('mongoose').Types.ObjectId;
    
    /**
     * True if provided object ID valid
     * @param {string} id 
     */
    function isObjectIdValid(id){ 
      return ObjectId.isValid(id) && new ObjectId(id) == id;
    }
    

提交回复
热议问题