Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

request - How to compare two dates with Mongodb (find query using NestJS)

I'm trying to get the list of posts for which the publish date is equal or less than the current date.

I'm using NestJS, Mongo & typeORM; which syntax should I use?

const posts =
  await this.mbRepository.find(
    { where: { "deletedAt": null , "publishDate" <= currentDate } }
  );

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

1 Answer

0 votes
by (71.8m points)

    let firstPoint = new Date();
    firstPoint.setHours(0);
    firstPoint.setMinutes(0);
    firstPoint.setSeconds(0);
    let lastPoint = new Date();
    lastPoint.setHours(23);
    lastPoint.setMinutes(59);
    lastPoint.setSeconds(59);

    const posts = await this.mbRepository.find({ publishDate: { $gte: firstPoint, $lt: lastPoint } } });

Get current day and make two point. One as begining of the day and another as end of the day. Then you can use mongodb operator $gte and $lt. In this way you will get all post which have been publish in this time range.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

31 comments

46.9k users

...