MongoDB 节点检查 objectid 是否有效 [英] MongoDB Node check if objectid is valid

查看:28
本文介绍了MongoDB 节点检查 objectid 是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Node 的驱动程序检查 ObjectID 是否有效

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

我试过了:

var BSON = mongo.BSONPure;
console.log("Validity: "  + BSON.ObjectID.isValid('ddsd'))

但我不断收到异常而不是真假.(异常只是一个 'throw e;//process.nextTick 错误,或第一个滴答时的 'error' 事件'

But I keep getting an exception instead of a true or false. (The exception is just a 'throw e; // process.nextTick error, or 'error' event on first tick'

推荐答案

这是一个简单的检查 - 不是 100% 万无一失

This is a simple check - is not 100% foolproof

如果要检查 24 个十六进制字符的字符串,可以使用此正则表达式.

You can use this Regular Expression if you want to check for a string of 24 hex characters.

var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")

checkForHexRegExp.test("i am a bad boy")
// false
checkForHexRegExp.test("5e63c3a5e4232e4cd0274ac2")
// true

正则表达式取自 github.com/mongodb/js-bson/.../objectid.ts

为了更好地检查使用:

var ObjectID = require("mongodb").ObjectID

ObjectID.isValid("i am a bad boy")
// false
ObjectID.isValid("5e63c3a5e4232e4cd0274ac2")
// true

isValid 代码 github.com/mongodb/js-bson/.../objectid.ts

这篇关于MongoDB 节点检查 objectid 是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆