How to get latest entries from MongoDB collection with Mongoose


Dev-Bookmarks Logo

Save up to a workweek a year by efficiently managing your dev bookmarks, on www.bookmarks.dev. Share your favorites with the community and they will be published on Github - Star


I have a use case where I need to retrieve the latest added public codingmarks. They are store in a mongo database, and I use Mongoose as ORM.

I want to have two possibilites to achieve this:

  1. specify the number of days to look back
  2. specify the timestamp since when to look forward

I think the code is self explanatory

/**
 * Returns the codingmarks added recently.
 * 
 * The since query parameter is a timestamp which specifies the date since we want to look forward to present time.
 * If this parameter is present it has priority. If it is not present, we might specify the number of days to look back via
 * the query parameter numberOfDays. If not present it defaults to 7 days, last week.
 *
 */
router.get('/latest-entries', async (req, res) => {
  try
  {

    if(req.query.since) {
      const bookmarks = await Bookmark.find(
        {
          createdAt: { $gte: new Date(parseFloat(req.query.since,0)) }
        }).sort({createdAt: 'desc'}).lean().exec();

      res.send(bookmarks);
    } else {
      const numberOfDaysToLookBack = req.query.days ? req.query.days : 7;

      const bookmarks = await Bookmark.find(
        {
          createdAt: { $gte: new Date((new Date().getTime() - (numberOfDaysToLookBack * 24 * 60 * 60 * 1000))) }
        }).sort({createdAt: 'desc'}).lean().exec();

      res.send(bookmarks);
    }

  }
  catch (err)
  {
    return res.status(500).send(err);
  }
});

Adrian Matei

Adrian Matei
Life force expressing itself as a coding capable human being

Lots of exciting dev bookmarks added in march 2019

Lots of exciting dev #bookmarks added in march 2019. Keywords: alias, api, api-management, architecture, arquillian, async, asynchronous, awesome, awesome-list, aws, bash, bootstrap, c, chai, cheatsheet, circuit-breaker, css, devops, diagnostics, diagram, dns, docker, docker-compose, docs, documentation, domain-driven-design, dotfiles, email, error-handling, facebook, favicon, ffmpeg, free-programming-books, functional-programming, gif, git, gradle, graph, helm, homebrew, html, html5, immutable.js, install, integration-testing, istio, java, javascript, jenv, junit, jvm, kotlin, kubernetes, kubernetes-helm, latex, linux, macos, markdown, maven-plugin, microservices, middleware, mocha, mongodb, monitoring, nginx, nodejs, oidc, online-tools, open-source, openid-connect, osx, package-manager, pandoc, performance, podcast, promise, proxy, r, reactive, reactive-programming, reactjs, redis, resources, rest, rxjs, security, shell, spring, spring-boot, spring-cloud, spring-cloud-gateway, spring-security, spring-webflux, sql, testing, tools, user-experience, video-processing, vim, visualization, web, websocket, windows and zuul Continue reading