node.js MongoDB 节点检查 objectid 是否有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11985228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB Node check if objectid is valid
提问by Akshat
How can I check whether an ObjectID is valid using Node's driver
如何使用 Node 的驱动程序检查 ObjectID 是否有效
I tried :
我试过 :
var BSON = mongo.BSONPure;
console.log("Validity: " + BSON.ObjectID.isValid('ddsd'))
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'
但是我不断收到异常而不是真假。(异常只是一个 'throw e; // process.nextTick 错误,或第一个滴答时的 'error' 事件'
回答by Gianfranco P.
Not sure where the isValid()function comes from but it's not in node-mongodb-native.
不确定isValid()函数来自哪里,但它不在node-mongodb-native 中。
You can use this Regular Expression if you want to check for a string of 24 hex characters.
如果要检查 24 个十六进制字符的字符串,可以使用此正则表达式。
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
checkForHexRegExp.test("badobjectid")
// false
checkForHexRegExp.test("5e63c3a5e4232e4cd0274ac2")
// true
Taken from github.com/mongodb/js-bson/.../objectid.js
回答by Eat at Joes
isValid()is in the js-bsonlibrary, which is a dependency of node-mongodb-native.
isValid()位于js-bson库中,它是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.
对于发现此问题的人,我不建议按照其他答案中的建议重新创建此方法。而是继续使用 node-mongodb-native 就像原始海报使用的那样,以下示例将访问isValid()js-bson 中的方法。
var mongodb = require("mongodb"),
objectid = mongodb.BSONPure.ObjectID;
console.log(objectid.isValid('53fbf4615c3b9f41c381b6a3'));
July 2018 update:The current way to do this is:
2018 年 7 月更新:目前的做法是:
var mongodb = require("mongodb")
console.log(mongodb.ObjectID.isValid(id))
回答by Sean McClory
As an extension of Eat at Joes answer... This is valid in node-mongodb-native 2.0
作为 Eat at Joes 答案的扩展......这在 node-mongodb-native 2.0 中有效
var objectID = require('mongodb').ObjectID
objectID.isValid('54edb381a13ec9142b9bb3537') - false
objectID.isValid('54edb381a13ec9142b9bb353') - true
objectID.isValid('54edb381a13ec9142b9bb35') - false
回答by jksdua
@GianPaJ's snippet is great but it needs to be extended slightly to cover non hex objectID's. Line 32 of the same file indicates objectID's can also be 12 characters in length. These keys are converted to a 24 character hex ObjectID by the mongodb driver.
@GianPaJ 的片段很棒,但需要稍微扩展以涵盖非十六进制对象 ID。同一文件的第 32 行表示 objectID 的长度也可以是 12 个字符。这些键由 mongodb 驱动程序转换为 24 个字符的十六进制 ObjectID。
function isValidObjectID(str) {
// coerce to string so the function can be generically used to test both strings and native objectIds created by the driver
str = str + '';
var len = str.length, valid = false;
if (len == 12 || len == 24) {
valid = /^[0-9a-fA-F]+$/.test(str);
}
return valid;
}
回答by argo
If you are using mongoosethen you can use mongoose for validation rather than depending on any other library.
如果您正在使用,mongoose那么您可以使用 mongoose 进行验证,而不是依赖于任何其他库。
if (!mongoose.Types.ObjectId.isValid(req.id)) {
return res.status(400).send("Invalid object id");
}
回答by Nishant
Below is my model where I am trying to validate subject id that is of type objectId data using JOI (Joi.objectId().required()):
下面是我尝试使用 JOI 验证 objectId 数据类型的主题 ID 的模型(Joi.objectId().required()):
const Joi = require('joi');
const mongoose = require('mongoose');
const Category = mongoose.model('Category', new mongoose.Schema({
name: {
type: String,
minlength: 5,
maxlength: 50,
required: true
},
thumbnail: {
type: String,
minlength: 5,
maxlength: 255,
required: true
},
subject_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Subject',
required: true
},
timestamp: {
type: Date,
required: true,
default: Date.now
}
}));
function validateCategory(category) {
const schema = {
name: Joi.string().min(5).max(50).required(),
subject_id: Joi.objectId().required(),
};
return Joi.validate(category, schema);
}
exports.Category = Category;
exports.validate = validateCategory;


joi-objectidvalidates that the value is an alphanumeric string of 24 characters in length.
joi-objectid验证该值是一个长度为 24 个字符的字母数字字符串。
回答by Randy Orton
Follow this regular expression :
遵循这个正则表达式:
in js
在js中
new RegExp("^[0-9a-fA-F]{23}$").test("5e79d319ab5bfb2a9ea4239")
new RegExp("^[0-9a-fA-F]{23}$").test("5e79d319ab5bfb2a9ea4239")
in java
在 Java 中
Pattern.compile("^[0-9a-fA-F]{23}$").matcher(sanitizeText(value)).matches()
Pattern.compile("^[0-9a-fA-F]{23}$").matcher(sanitizeText(value)).matches()
回答by technology_dreamer
You can use Cerberusand create a custom function to validate and ObjectId
您可以使用Cerberus并创建自定义函数来验证和 ObjectId
from cerberus import Validator
import re
class CustomValidator(Validator):
def _validate_type_objectid(self, field, value):
"""
Validation for `objectid` schema attribute.
:param field: field name.
:param value: field value.
"""
if not re.match('[a-f0-9]{24}', str(value)):
self._error(field, ERROR_BAD_TYPE % 'ObjectId')
## Initiate the class and validate the information
v = CustomValidator()
schema = {
'value': {'type': 'objectid'}
}
document = {
'value': ObjectId('5565d8adba02d54a4a78be95')
}
if not v(document, schema):
print 'Error'

