Node JS and MongoDB - Return data from a model to a route

0

I'm new with Node JS + MongoDB and I have a question about two days that I could not figure out how to solve it.

My problem is this:

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

Route 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 archive:

'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 do not know how I can return the model result to the route and display JSON object in the user's browser.

Could someone give me a light?

    
asked by anonymous 03.04.2017 / 14:47

1 answer

1

Hello, first point Bruno, use an ODM to perform the database operations with MongoDB (Mongoose, sequelize, etc ...)

Second point, the pageList callback function is always returning to the empty caller. That is, empty for error and blank for docs.

change the implementation to:

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

        if (err) {
            return cb(err);
        } else {
            return cb(null,hotels);
        }
    })  
} 

Once this is done, check the callback to the pageList method on the instance of hotels in the route file. The same should contain all hotels (if in fact exist in bank rs).

Last remark, you still have only one error handler, in case you always return the object (msg: 'implementation not found') with status 404. p>

Soon, this information will be sent to the customer only if the callback returns the completed hotel array. To manage the return, do something like:

if(err || !docs) return res.send({code:500,msg:"Ops... Something wrong..."}); 
return res.send({code:200,msg:docs})

Well, I think this should solve your problem.

    
03.04.2017 / 18:26