简体   繁体   English

如何从一个函数中的多个模式中检索和传递数据

[英]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. 我是expressjs中的新手,想知道如何从控制器中的多个模式中检索和传递数据。

here is the case, pretend i wanna open add_new_blog page and below is the router; 就是这种情况,假装我想打开add_new_blog页面,下面是路由器;

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

well then in BlogController.index i need to retrieve Category and Tag Models. 那么在BlogController.index中,我需要检索类别和标签模型。

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. 您可以使用Promise.all() ,获取两个猫鼬调用数据,然后进行渲染。

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 });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在javascript中通过引用传递变量? 从ActiveX函数读取数据,返回多个值 - How to pass variable by reference in javascript? Read data from ActiveX function which returns more than one value 从角度指令向控制器函数传递多个参数 - Pass more than one arguments to controller function from angular directive 如何在React的组件函数中传递多个参数 - How to pass more than one argument in component function in React 将多个控件传递给Javascript函数 - Pass More than One Control to Javascript Function 如何通过ajax向PHP传递和检索JSON函数作为数据? - How to pass and retrieve JSON function as data via ajax to PHP? 帮助程序 function 从 object 检索值失败,object 中存在多个项目 - Helper function to retrieve a value from an object fails with more than one item in the object 你能在 React 中将多个 arguments 传递给 Function 组件吗? 如果是,比怎么样? - Can you pass more than one arguments to Function Component in React? If yes than how? 如何从Firebase中的函数取回数据 - How to retrieve data back from a function in firebase 如何在函数Meteor.loginWithFacebook()上传递更多数据? - How to pass more data on function Meteor.loginWithFacebook()? 仅当用户在页面上停留一秒钟以上时,才检索数据 - How to retrieve data only if user stay more than one second on the page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM