$gte / $lte filters not working in lokijs

56 Views Asked by At

I am generating query based on user input and passing it onto LokiJS to handle. However, query doesn't seem to take effect (everything is returned as it is).

Logic to generate query :-

function prepareQueryFromOptions(options: GetAllTransactionsOptions) {
  const query: Record<string, any> = {
    timestamp: {
      "$gte": options.dateRange.from.getTime(),
      "$lte": options.dateRange.to.getTime(),
    },
  };
  if (options.accounts) {
    query.accountId = {
      "$in": options.accounts,
    };
  }
  if (options.categories) {
    query.category = {
      "$in": options.categories,
    };
  }

  return query;
}

Using above function as below:

const query: Record<string, any> = prepareQueryFromOptions(options);

const transactions: Transaction[] = transactionsCollection.chain().find(query).simplesort('timestamp').data();

My Failing Testcase:

const AUG_1_2022 = new Date(2022, 7, 1);
const AUG_5_2022 = new Date(2022, 7, 5);
const AUG_12_2022 = new Date(2022, 7, 12);

it('getAllTransactions()', async () => {
    let txs1 = await transactions.getAllTransactions({
      dateRange: {
        from: AUG_1_2022,
        to: AUG_12_2022,
      },
    });
    expect(txs1.length).toBe(2); // Successful (Both transactions are returned)

    let txs = await transactions.getAllTransactions({
      dateRange: {
        from: AUG_1_2022,
        to: AUG_5_2022,
      },
    });
    expect(txs.length).toBe(1); // Failed since again both the transactions are returned
  });
1

There are 1 best solutions below

0
On BEST ANSWER

I guess the right move will be to use $between instead. See this. In your example:

function prepareQueryFromOptions(options: GetAllTransactionsOptions) {
  const query: Record<string, any> = {
    timestamp: {
      "$between": [
          options.dateRange.from.getTime(),
          options.dateRange.to.getTime(),
      ],
    },
  };
  if (options.accounts) {
    query.accountId = {
      "$in": options.accounts,
    };
  }
  if (options.categories) {
    query.category = {
      "$in": options.categories,
    };
  }

  return query;
}