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

Asked

Viewed 893 times

0

I’m new to Node JS + Mongodb and I’ve had a doubt for a couple of days that I couldn’t figure out how to solve it.

My problem is this:

I have a file of routes that make a call to a model, as in the example below:

Route archive:

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

        })
    })
}

Model 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 don’t know how to return the model result to the route and display JSON object in the user’s browser.

Someone could give me a light?

1 answer

1


Ola, first point Bruno, use an ODM to perform database operations with Mongodb (Mongoose, sequelize, etc...)

second point, pageList callback function is always returning to the empty Caller. That is, empty for error and empty 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 return of the call to the pageList method in the hotel instance in the route file. It should contain all hotels (if in fact it exists in the bank rs).

Last remark, still in the callback function for pageList in the order of routes, you have only one error Handler, in case vc always returns the object { msg: 'implementation not found' } with status 404.

soon, only this information will be sent to the customer even if the callback returns the filled array of hotels. 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 that should solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.