如何使用NeDB解决FeathersJS前端日期查询

问题描述 投票:0回答:1

在使用Feathers客户端的前端应用程序上,我试图按日期过滤数据:

rides = await client.service('rides').find({
  query: {
    date: {
      ...past ? { $lt: new Date().getTime() } : { $gte: new Date().getTime() },
    },
    $sort: {
      date: past ? 1 : -1,
    },
  },
}).then(result => result.data);

这不起作用,给我零结果。

我在official issue上发现这是因为查询是作为字符串传递的,并且NeDB需要数据库。

此关于羽毛api钩的破解确认了此问题:

// On find.before hook
if (params.query && params.query.date.$gte) {
  params.query.date.$gte = new Date(params.query.date.$gte);
}
if (params.query && params.query.date.$lt) {
  params.query.date.$lt = new Date(params.query.date.$lt);
}

但这不是在任何字段上进行可靠查询的可靠解决方案。

处理它的最佳方法是什么?

date feathersjs nedb
1个回答
0
投票

我在全局应用程序挂钩上找到了更好的通用解决方法:

import { HookContext } from '@feathersjs/feathers';
import _ from 'lodash';

export default {
  before: {
    find: [
      (context: HookContext) => {
        const { params } = context;
        const dateFormatRegex = 

        const mapper = (value: any): any => {
          // Recursive call of the mapper
          if (_.isPlainObject(value)) {
            return _.mapValues(value, mapper);
          }
          // String date to Date object transform.
          if (dateFormatRegex.test(value)) {
            return new Date(value);
          }
          return value;
        };

        if (params.query) {
          params.query = _.mapValues(params.query, mapper);
        }
      },
    ],
  },
};

然后在前端客户端上,将new Date().getTime()替换为new Date().toISOString()

它可以工作,但是我发现这有点笨拙,我很惊讶这不是由Feathers或NeDB自己管理的,也许我缺少了什么?

© www.soinside.com 2019 - 2024. All rights reserved.