Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
Node JS + MongoDB - How to return data from model to a route?

I'm starting with NodeJS + MongoDB and I have a question about a couple of days that I could not figure out how to solve it.

My problem is:

I have a route file that makes a call to a model, as in the example below:

Routes file:

'use strict';

module.exports = function(app) {
app.get('/api/hotels/', function(req, res) {
    let hotels = new app.model.Hotels();

        hotels.pageList(req.params.page, req.params.qtd, (err, docs) => {

            res.status(404).json({
                msg: 'implementation not found'
            })

        })
    })
}

Models file:

'use strict';

function Hotels() {
    this._hotels = process.db.get().collection('hotels')
    this._ObjectID = process.db.ObjectID()
}

Hotels.prototype.pageList = function(page, qtd, cb) {
    //list all hotels
    this._hotels.find(function(err, hotels) {

        if (err) {
            return err;
        } else {
            return hotels;
        }
    })

    cb()
}

module.exports = function() {
    return Hotels
}

The problem is that I'm not sure how I can return the model result to the route and display JSON object in the user's browser.

can anybody help me?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Try it like this:

Hotels.prototype.pageList = function(page, qtd, cb) {
    //list all hotels
    this._hotels.find(function(err, hotels) {

         cb(err, hotels);
    });   
}

Then, in your route you can do this:

app.get('/api/hotels/', function(req, res) {
    let hotels = new app.model.Hotels();

        hotels.pageList(req.params.page, req.params.qtd, (err, hotels) => {
          if(err)
            res.status(404).json({
                msg: 'implementation not found'
            });

          res.json(hotels);
        })
    })
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda