Luiz Picolo
Luiz Picolo

Reputation: 113

Send data from two models to a view

I have a Category template and another Product. Preceded to return these models in a single view

router.get('/', function(req, res, next) {
  Category.find({}, function(error, data){
    // something 
  });

  Product.find({}, function(error, data){
    // something
  }); 

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

Upvotes: 1

Views: 172

Answers (3)

Wasiq Muhammad
Wasiq Muhammad

Reputation: 3118

As Mongoose and Sequelize both support Promises.First you need to query all the categories and products and save it temporary in variable then before sending your response create and object and send it. Here is an example. I would prefer async/awit it makes your code more readability and saves you from then() chaining.

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


});

It also better, if you make Repository layer for querying your database. Also Use any design pattern for project structure

Upvotes: 1

Teneff
Teneff

Reputation: 32158

Most of the object model libraries like Mongoose or Sequelize support Promises and probably you would be able to do something like this

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

Otherwise you'd be able to create your own promises like this:

router.get('/', function(req, res, next) {

  const categoryPromise = new Promise((resolve, reject) => {
    Category.find({}, function(error, data){
      error ? reject(data) : resolve(data);
    });
  })


  const productPromise = new Promise((resolve, reject) => {
    Product.find({}, function(error, data){
      error ? reject(data) : resolve(data);
    });
  })

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

Upvotes: 1

1565986223
1565986223

Reputation: 6718

Set mongoose's pormise to use es6 Promise like mongoose.Promise = global.Promise, then you can use async/await to query both model and render.

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

Upvotes: 0

Related Questions