MongoDB Node check if objectid is valid

前端 未结 8 2422
甜味超标
甜味超标 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:13

    isValid() is in the js-bson (objectid.ts) library, which is a dependency of node-mongodb-native.

    For whoever finds this question, I don't recommend recreating this method as recommend in other answers. Instead, continue using node-mongodb-native like the original poster was using, the following example will access the isValid() method in js-bson.

    var mongodb = require("mongodb");
    var objectid = mongodb.BSONPure.ObjectID;
    
    console.log(objectid.isValid('53fbf4615c3b9f41c381b6a3'));
    

    July 2018 update: The current way to do this is:

    var mongodb = require("mongodb")
    console.log(mongodb.ObjectID.isValid(id))
    

提交回复
热议问题