'koa doesn't render a page (404) after mongodb request

I am trying to render a page with something I load from MongoDB:

  router.get('/messages', async (ctx, next) => {
   await MessageModel.find()
  .then((result:any) => {
    ctx.render('index', {
      title: 'Messages',  
      messages: result
    })
  });

});

I got 404 message after I go to /messages but it works fine when I render it without approaching to DB:

  router.get('/messages', async ctx => {
    await ctx.render('index', {
      title: 'Messages'
    })
 }); 

Sorry for my 'noob' question, I am just making my first steps into coding. Thanks for help.



Solution 1:[1]

You should await for models result or consume them with .then(), not both at the same time. Try this:

  router.get('/messages', async (ctx, next) => {
   let result = await MessageModel.find()
   await ctx.render('index', {
     title: 'Messages',  
     messages: result
   })
  })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user14967413