stalniy/ucast

[mongo2js] - Nested object match

Closed this issue · 2 comments

Hello,
Thank you for this very useful package.

I have a problem with a query supported within mongodb but not within the package.

const store = [{ foo: { bar: 'value' }}];
const predicate = guard({ foo: { bar: 'value' }} as any); // any to avoid typing error
const result = store.filter(predicate);

but it works with:

const store = [{ foo: { bar: 'value' }}];
const predicate = guard({ 'foo.bar': 'value' } );
const result = store.filter(predicate);

Result:
image

Is it easy to fix ?

Hey,

ucast doesn't support object matching from the box. I think it's mainly redundant and very very rarely used. I think you can replace it with this:

const predicate = guard({ 'foo.bar': 'value' })
const result = store.filter(predicate);

Dot notation should give you result which you need

However it's possible to implement it by yourself by providing custom compare option to createFactory function:

import {
  allParsingInstructions,
} from '@ucast/mongo';
import {
  allInterpreters,
  compare
} from '@ucast/js';
import isEqual from "lodash/isEqual";

const myGuard = createFactory(allParsingInstructions, allInterpreters, {
  compare: (a, b) => {
     if (typeof a === "object" && typeof b === "object") {
       return isEqual(a,b) ? 0 : 1;
     }
     
     return a > b ? 1 : -1
  }
})