首页 > 解决方案 > Render two MongoDB data to an EJS file

问题描述

It's one of the data which I want to send to myaccount.ejs

app.get("/myaccount", (req, res)=>{
  if(req.isAuthenticated()){
  const user_files = File.find();
    user_files.exec(function(err, data1){
      if(err){
        console.log(err);
      } else {
          res.render("myaccount", {file: data1});
      }
    })

This code below is the second data I want to send to myaccount.ejs.

app.get("/myaccount", (req, res)=>{
  if(req.isAuthenticated()){
  const user = User.find();
    user.exec(function(err, data2){
      if(err){
        console.log(err);
      } else {
          res.render("myaccount", {user: data2});
      }
    })

How can I send both of them together to my ejs file.

标签: javascriptnode.jsjsonmongodbejs

解决方案


You can use async/await for cleaner code.


app.get("/myaccount", async (req, res, next)=>{
 try {
   if(!req.isAuthenticated()){
     throw new Error('Not Authenticated!');
   }
   const file = await File.find({}).exec();
   const user = await User.find({}).exec();

   if(!file || !user){
    throw new Error('User or file not found.')
   }
 
   res.render("myaccount", {user, file});
 }
 catch(err){
   return next(err);
 }

})



推荐阅读