将两个模型中的数据发送到视图

时间:2019-04-07 05:18:43

标签: node.js express

我有一个类别模板和另一个产品。在单个视图中返回这些模型之前

/etc/fstab

3 个答案:

答案 0 :(得分:1)

大多数对象模型库(例如Mongoose或Sequelize)都支持Promises,也许您可​​以执行类似的操作

component

否则,您将可以像这样创建自己的承诺:

router.get('/', function(req, res, next) {
  const categoryPromise = Category.find({});

  const productPromise = Product.find({}); 

  Promise.all([
    categoryPromise,
    productPromise,
  ]).then(([
    products,
    categories
  ]) => {
    res.render('produtos/index', { 
      categories,
      products
    });
  })
});

答案 1 :(得分:1)

作为猫鼬 Sequelize 都支持Promises。首先,您需要查询所有类别和产品并将其临时保存在变量中,然后再发送响应创建和对象并发送。这是一个例子。我更喜欢async / awit,它可以使您的代码更具可读性,并避免您then()链接。

router.get('/', async function(req, res, next) {
  let category, products;
  try {
    category = await Category.find({});
    products = await Product.find({});

    res.render('products/index', { 
    categories: category,
    Products: products

  });
  } catch (e) {
    return next(e)
  }


});

如果您制作 Repository 层来查询数据库,也会更好。也可以将任何设计模式用于项目结构

答案 2 :(得分:0)

将猫鼬的色情设置为使用Promise之类的es6 mongoose.Promise = global.Promise,然后可以使用async/await来查询模型和渲染。

// note async
router.get('/', async function(req, res, next) {
  let categories, product;
  try {
    category = await Category.find({});
    products = await Product.find({});
  } catch (e) {
    return next(e)
  }

  res.render('produtos/index', { 
    categories: categories,
    Products: products
  });
});