1

Currently I have a timestamp field with value format like 1479664146607.

What I wanted to do is to get all data with timestamp that has a year of let's say 2017.

My current code is non-performant. It gets all the data, and then uses a filter method.

Let's say I got 2000+ records.

const records = []; // all records
const data = records.filter(r => new Date(r).getYear == '2017');

While this code works, it kills the server.

My database is nedb and using feathersjs, I can actually get equality items by

app.service('messages').find({
  query: {
    timestamp: '2017'
  }
});

This code will not work because it will search for the exact year. I am looking for a way to convert the timestamp field to a year before searching it in the database.

halfer
  • 19,824
  • 17
  • 99
  • 186
wobsoriano
  • 12,348
  • 24
  • 92
  • 162

1 Answers1

2

Okay, so what I did is to use the $gt and $lt operators.

Let's say we want to get all data in year 2018.

Using momentjs, I did something like this:

    const year = '2018';

    // Get previous year based on given year
    const previousYear = moment(year, 'YYYY').subtract(1, 'year').format('YYYY');
    // Get next year based on given year
    const nextYear = moment(year, 'YYYY').add(1, 'year').format('YYYY');

    // get full ending date of previous year
    const endOfPreviousYear = moment(previousYear, 'YYYY').endOf('year').format('x');
    // get full starting date of next year
    const startOfNextYear = moment(nextYear, 'YYYY').startOf('year').format('x');

    // get data where year is greater than `endOfPreviousYear` and less than `startOfNextYear`
    const yearQuery = {
        $gt: +endOfPreviousYear,
        $lt: +startOfNextYear
    }

    app.service('messages').find({
        query: {
            timestamp: yearQuery
        }
    });
wobsoriano
  • 12,348
  • 24
  • 92
  • 162