Can I determine if a string is a MongoDB ObjectID?

前端 未结 16 724
时光说笑
时光说笑 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:44

    I have used the native node mongodb driver to do this in the past. The isValid method checks that the value is a valid BSON ObjectId. See the documentation here.

    var ObjectID = require('mongodb').ObjectID;
    console.log( ObjectID.isValid(12345) );
    

提交回复
热议问题