0

I am trying to to build a mongoose query to find records that match one date, i think its working but it doesn't show anything because the date i have in my array of objects is string and i am using date to compare them.

const startDate = new Date(new Date(req.query.date).setHours(0, 0, 0));
const endDate = new Date(new Date(req.query.date).setHours(23, 59, 59));
const transactions = await Transaction.paginate({ 'payments.date': { $gte: startDate, $lte: endDate } }, { allowDiskUse: true, page: req.query.page });

Here's the schema for payments object

payments: [
    {
        payment_system: {
            type: String,
        },
        amount: {
            type: Number,
        },
        date: {
            index: true,
            type: String,
        },
    },
],

As you can see the date is string, and its indexed. The reason i put it as a string because it would keep the server time instead of the timezone i desired. But that's not the problem the problem is to filter these results by date which is string. Can anyone help me?

Thank you

3
  • I guess this is what you are looking for stackoverflow.com/a/51984693/11283638 Commented Mar 8, 2021 at 13:13
  • I would recommend moment.js, then it would be startDate = moment().startOf('day').toDate() and endDate = moment().endOf('day').toDate() Commented Mar 8, 2021 at 13:37
  • @Ashutoshpatole just tried that but i am getting an error An object representing an expression must have exactly one field: Commented Mar 8, 2021 at 13:58

1 Answer 1

0

Here's a working example

const startDate = moment(req.query.createdDate).startOf('day');
const endDate = moment(req.query.createdDate).endOf('day');
const transactions = await Transaction.paginate(
        {
            'payments.date': {
                $gte: startDate.toDate().toISOString(),
                $lt: endDate.toDate().toISOString(),
            },
        },
        { allowDiskUse: true, page: req.query.page }
    ); 

Following code works fine for me, in combination with mongoose-v2-paginate. Works if you have string timestamps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.