简体   繁体   中英

Mongoose find by date in array of objects string date

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM