Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

javascript - Query by date range using Mongoose for dates that have format MM/DD/YY h:m and type String

I have a schema like this

    const someSchema = new mongoose.Schema (
{
   updatedAt: { type: string }
}, { timestamps: { currentTime: () => moment().format("MM/DD/YY, h:mm") } }

);

I want to query this collection to find the documents updated within a date range for example: 12/05/20 to 12/31/20, hours and minutes don't matter. My startDate and endDate is in the YYYY-MM-DD format. I have tried to find

updatedAt: {
                    $gte: new Date(startDate),
                    $lte: new Date(endDate)
                }

or

updatedAt: {
                        $gte: startDate,
                        $lte: endDate
                    }

but they are not working. Thank you for your time!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First try to alter moment().format("MM/DD/YY, h:mm") to moment().format("MM/DD/YY, HH:MM:SS")

then

updatedAt: { $gte: new Date(startDate).setHours(0,0,0,0)
             $lte: new Date(endDate).setHours(0,0,0,0)},

You are declaring moment().format as a datetime but when you create Date() object you are passing only the date!

When you are practicing date manipulation better use milliseconds and UTC notation. It is something universal to all type of databases. Avoid to use varchar type to store date as strings.

Give it a try!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...