V
V
Vitaly the Wise2017-07-08 17:05:20
MongoDB
Vitaly the Wise, 2017-07-08 17:05:20

How to query a database on a page?

I want to enter the query result into a dropdown list (select - option).
Here is the model:
let db = require('../db');
exports.getAll = function(callback) {
db.get().collection('regions').find({
value: {
$ne: 0
}
}).toArray(function(error, docs) {
callback(error, docs );
});
};
Here is the controller:
let regionsModel = require('../models/regions');
exports.getAll = function(request, response) {
regionsModel.getAll(function(error, docs) {
if (error) {
console.log(error);
return response.sendStatus(500);
}
response.send(docs);
});
};
Here is the routing:
app.get('/', function(request, response) {
response. render('pages/index', {regions: regionsController.getAll});
});
But, on the page, enter this - function (request, response) { regionsModel.getAll(function(error, docs) { if (error) { console.log(error); return response.sendStatus(500); } response.send( docs); }); } - snippet from controller.
Help me please. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2017-07-09
@tapinambur0508

app.get('/', function(request, response) {
    response.render('pages/index', { regions: regionsController.getAll() });
});

But given that there is asynchronous data retrieval from the database in the controller, then most likely nothing will come of it. First you need to get the data from regionsController.getAll(), and then call res.render inside with the received data.
Or just move response.render() to the controller and call it from the route.
let regionsModel = require('../models/regions');

exports.getAll = function(request, response) {
regionsModel.getAll(function(error, docs) {
    if (error) {
        console.log(error);
        return response.sendStatus(500);
}

    response.render('pages/index', { regions: docs });
});
};

const controller = require('./controller');

app.get('/', function(request, response) {
    controller.getAll(request, response);
});

Something like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question