Home > database >  Is it possible to send multiple data in one view on Node JS?
Is it possible to send multiple data in one view on Node JS?

Time:12-13

I am trying to pass several data to one view. I can send the products to it but I would like to send the categories as well. I want to send them separately and not with a join. I have been advised to put it after the "then" but I don't know how to do it.

router.get('/', function (req, res) {
  models.produit.findAll(
    {
      include: 
      [
        {
          model: models.image, as: "images" 
        },
        {
          model: models.promotionproduit, as: "promotionproduits",
          include:[{model: models.promotion, as: "Promotion"}]
        }
      ]})
      .then(data => {
        res.render('home', {
          data: data
        });
      
    }).catch(err => console.log(err));
});

CodePudding user response:

Sure, use async/await to build up your data then pass it to the view.

router.get('/', async(req, res) => {

  // define your data var
  const data = {
    errors: {}
    produits: [],
    categories: []
  }

  // get produits
  try {
    data.produits = await models.produit.findAll({
      include: [{
          model: models.image,
          as: "images"
        },
        {
          model: models.promotionproduit,
          as: "promotionproduits",
          include: [{
            model: models.promotion,
            as: "Promotion"
          }]
        }
      ]
    })
  } catch {
    data.errors.produits = 'Échec du chargement des produits.'
  }

  // get categories
  try {
    // as above, do your model...
  } catch {
    data.errors.categories = 'Échec du chargement des catégories.'
  }

  res.render('home', {
    data
  });
});

  • Related