Can I determine if a string is a MongoDB ObjectID?

前端 未结 16 687
时光说笑
时光说笑 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 01:00

    @ross-u answer is just amazing.

    I have chained the methods to do a full validation inline:

    documentId = id && isValid(id) && new ObjectId(id) == id ? id : null
    

    Note the double equal sign, which is VERY important as new ObjectId() does not return a string and strict comparison will return false when compared against a normal string (which I had coming in my logic).

    The methods have been destructured from the mongoose object exposed by the require:

    const {
      Types: {
        ObjectId: { isValid },
        ObjectId
      }
    } = require("mongoose");
    

提交回复
热议问题