Chukwuma Kingsley
Chukwuma Kingsley

Reputation: 527

how to call one model from another route

please i have a question. i have tried to implement this for more than four hours but it didn't work. I am working with Node, express, mongoose and ejs template How do i call a model to fetch all the data inside it from another route file.

For example:

i have Post model and the post.js file is inside model folder.

and i have index.js router, and the index.js file is inside routes folder

inside the routes/index.js file i want to fetch all the posts inside Post Model when home page is loaded so that i can display them on my layout file(landing page)

GET HOME PAGE AND RENDER POSTS ALONG

router.get('/', function(req, res, next) {
  const allposts = Post.find({})
  res.render('index', {
   allposts: allposts
  });
});

The reason i am taking this approach is because i want to display my newest post blogs on my layout file(landing page) but when i include the posts index file on my layout it says that my posts is undefined, so i have decided to take a different approach to accomplish this. if you know how i can get this done, please help me or any other method that i can use to accomplish this.

Upvotes: 0

Views: 245

Answers (1)

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

Mongo queries are asynchronous. So when you return the response, the Post.find() query has not been completed. You can use callbacks, promises or async/await to control the flow.

// require Post model
const Post = require('../model/post'); 

router.get('/', function(req, res, next) {
    Post.find()
    .then(allposts => {
        res.render('index', {allposts});
    })
    .catch(err => {
        console.log(err);
    })
});

Upvotes: 1

Related Questions