mongodb - filter by objectId imrpoved

This commit is contained in:
SPRINX0\prochazka
2025-04-30 08:36:56 +02:00
parent 9d376961f4
commit 62ddbb20ac
2 changed files with 36 additions and 7 deletions

View File

@@ -52,6 +52,18 @@ const binaryCondition =
};
};
const simpleEqualCondition = () => value => ({
conditionType: 'binary',
operator: '=',
left: {
exprType: 'placeholder',
},
right: {
exprType: 'value',
value,
},
});
const likeCondition = (conditionType, likeString) => value => ({
conditionType,
left: {
@@ -348,6 +360,8 @@ const createParser = (filterBehaviour: FilterBehaviour) => {
objectid: () => token(P.regexp(/ObjectId\(['"]?[0-9a-f]{24}['"]?\)/)).desc('ObjectId'),
objectidstr: () => token(P.regexp(/[0-9a-f]{24}/)).desc('ObjectId string'),
hexstring: () =>
token(P.regexp(/0x(([0-9a-fA-F][0-9a-fA-F])+)/, 1))
.map(x => ({
@@ -366,6 +380,7 @@ const createParser = (filterBehaviour: FilterBehaviour) => {
value: r => P.alt(...allowedValues.map(x => r[x])),
valueTestEq: r => r.value.map(binaryCondition('=')),
hexTestEq: r => r.hexstring.map(binaryCondition('=')),
valueTestObjectIdStr: r => r.objectidstr.map(simpleEqualCondition()),
valueTestStr: r => r.value.map(likeCondition('like', '%#VALUE#%')),
valueTestNum: r => r.number.map(numberTestCondition()),
valueTestObjectId: r => r.objectid.map(objectIdTestCondition()),
@@ -546,12 +561,13 @@ const createParser = (filterBehaviour: FilterBehaviour) => {
}
}
if (filterBehaviour.allowNumberDualTesting) {
allowedElements.push('valueTestNum');
if (filterBehaviour.allowObjectIdTesting) {
allowedElements.push('valueTestObjectIdStr');
allowedElements.push('valueTestObjectId');
}
if (filterBehaviour.allowObjectIdTesting) {
allowedElements.push('valueTestObjectId');
if (filterBehaviour.allowNumberDualTesting) {
allowedElements.push('valueTestNum');
}
// must be last

View File

@@ -11,6 +11,21 @@ function convertRightOperandToMongoValue(right) {
throw new Error(`Unknown right operand type ${right.exprType}`);
}
function convertRightEqualOperandToMongoCondition(right) {
if (right.exprType != 'value') {
throw new Error(`Unknown right operand type ${right.exprType}`);
}
const { value } = right;
if (/^[0-9a-fA-F]{24}$/.test(value)) {
return {
$in: [value, { $oid: value }],
};
}
return {
$eq: value,
};
}
function convertToMongoCondition(filter) {
if (!filter) {
return null;
@@ -28,9 +43,7 @@ function convertToMongoCondition(filter) {
switch (filter.operator) {
case '=':
return {
[convertLeftOperandToMongoColumn(filter.left)]: {
$eq: convertRightOperandToMongoValue(filter.right),
},
[convertLeftOperandToMongoColumn(filter.left)]: convertRightEqualOperandToMongoCondition(filter.right),
};
case '!=':
case '<>':