简体   繁体   中英

how to retrieve and pass data from more than 1 Schema in a function

im newbie in expressjs and wondering how to retrieve and pass data from more than 1 schema in my controller.

here is the case, pretend i wanna open add_new_blog page and below is the router;

router.get('/add_new_blog', BlogController.index);

well then in BlogController.index i need to retrieve Category and Tag Models.

const Category = require('models/categorySchema');
const Tag = require('models/tagSchema');

module.exports = {

  index(req, res, next){

    Category.find({});
    Tag.find({});

    // how to find/retrieve data from both Schema then i pass them to Views.


    res.render('/blog/blogForm');
  }
}

The Question is What the coding will look like to retrieve the data from both then pass it to the view?

You can use Promise.all() , get the two mongoose calls data and then render it.

const categoryFind = Category.find({}).exec(); // exec() returns a Promise.
const tagsFind = Tags.find({}).exec();

Promise.all(categoryFind, tagsFind).then((values) => {
  res.render('/blog/blogForm', { categories: values[0], tags: values[1] });
});

Notice that I render inside the callback, that is because mongoose calls are asynchronous. Otherwise you will be rendering before the queries have completed.

That is the same as:

Category.find({}, (err, catData) => {
  Tags.find({}, (err, tagsData) => {
    res.render('/blog/blogForm', { categories: catsData, tags: tagsData });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM