How to return data from different models from Nodejs and MongoDD?

0

Good morning, I have a web application made in Nodejs, in one of the requests I must send data of different models. My query is as follows Is this the correct way?

function getProduct (req, res) {
  let productId = req.params.productId
  Product.findById(productId, (err, product) => {
    if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})
    if (!product) return res.status(404).send({message: 'No existen productos'})
    Company.find({}, (err, companies) => {
      if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})
      if (!companies) return res.status(404).send({message: 'No existen compañias'})
      res.status(200).send({product: product, companies: companies})
    })
  })
}
    
asked by Alvaromero 03.02.2017 в 23:06
source

1 answer

0
  

Is this the right way?

No. There is an error with that code and that is, you respond twice to a single request . What you should do is save the documents of each collection you iterate in an object and, in the last callback, send your answer.

Note: to avoid a callback hell I recommend using promises .

function getProduct (req, res) {
  let productId = req.params.productId

  Product
    .findById(productId)
    .then((product) => {
      Company
        .find()
        .then((companies) => {
          res.jsonp({
            product,
            companies
          });
        })
        .catch(handleError.bind(this, res));
    })
    .catch(handleError.bind(this, res));
}

function handleError (res, e) {
  res
    .status(500)
    .jsonp({
      errors: [
        message: 'Ha ocurrido un error. Intente más tarde',
        detail: e.message
      ]
    });
}

And in the client, for example if you are doing an API, you consume it with AJAX:

fetch ('/products/${productId}')
  .then((res) => {
    if (res.ok) {
      res.json().then(({ product, companies }) => {
        // hacer algo con product y companies
      });
    } else {
      res.json().then(({ errors }) => {
        // manejar los errores
      });
    }
  });
    
answered by 05.02.2017 / 15:48
source