Home > Software design >  koa doesn't render a page (404) after mongodb request
koa doesn't render a page (404) after mongodb request

Time:05-08

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.

CodePudding user response:

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
   })
  })
  • Related