Not able to call promise that is returned from within a function

  es6-promise, express, javascript, node.js

I have a function in the middleware file called setSignedInUser which receives a cookie as a parameter. I want to find a user saved in the SignedIn collection with the cookie,retrieve the user’s unique id ,search for the user’s complete information from the Users collection and return the foundUser which I would like to access in another file where the function is called from.

The middleware file:

const { resolve } = require('path');
const User = require('./Models/User'),
      SignedIn = require('./Models/SignedIn');

module.exports = {
   setSignedInUser : (cookie)=>{
      console.log(cookie)
    SignedIn.findOne({secretToken : cookie})
    .then(foundSignIn=>{
        userId = foundSignIn.userId;
        User.findOne({_id : userId})
        .then(foundUser=>{
            console.log(foundUser) // User is successfully found and loged to the console
            return new Promise((resolve , reject)=>{
                if(foundUser){
                    resolve(foundUser);
                }else{
                    reject('error')
                }
            })
        })
        .catch(err=>{
            console.log(err)
        })
    })
    .catch(err=>{
        console.log(err)
    })
  }
}

I call this function from the index.js file where my route is.

The index.js file:

const middleware = require('../middleware');
router.get('/' , (req , res)=>{
  middleware.setSignedInUser(req.cookies.auth_cook)
  .then(foundUser=>{
     console.log(foundUser)
  })
  .catch(err=>{
    console.log(err)
  })
 res.render('../views/general/home.ejs' , {user : user})
});

But here I get an error saying Cannot call .then on undefined

What am I missing here? Thankyou

Source: Ask Javascript Questions

LEAVE A COMMENT