Problem using javascript, JOD NODE and CSV database

1

Hello

I'm doing a project for school using IBM's Bluemix and I'm having some problems finding my error. I am using a database in CSV that has as parameters the neighborhood, number of rooms, area in square meters, price among other information of apartments. I also have a JADE file that contains a form to be populated by the user on my main page. Once completed, my app.js should be able to cross the information provided by the user (number of rooms he wants, maximum value that he is willing to pay) with the database, returning on another page the base apartment list of data that fit what the user requested.

However, for some reason, this is not happening. I think the error might be in some of these lines:

  var resultado = {Bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};

  for (var i = 1; i < dados.Bairro.length; i++){

      if (dados.Bairro[i] == parametros.bairro && dados.quartos[i] == parametros.quartos && dados.area[i] >= Number(parametros.area) && dados.valor[i] <= Number(parametros.valor)){

Please find attached my code. Thank you so much!

/*eslint-env node*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

var fs = require('fs');

var parse = require('csv-parse');

// create a new express server
var app = express();

function seleciona_dados(dados, parametros){
    var resultado = {Bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};
        for (var i = 1; i < dados.Bairro.length; i++){
            if (dados.Bairro[i] == parametros.bairro && dados.quartos[i] == parametros.quartos && dados.area[i] >= Number(parametros.area) && dados.valor[i] <= Number(parametros.valor)){
                resultado.bairro.push(dados.bairro[i]);
                resultado.quartos.push(dados.quartos[i]);
                resultado.area.push(dados.area[i]);
                resultado.valor.push(dados.valor[i]);
                resultado.endereco.push(dados.endereco[i]);
                resultado.img.push(dados.img[i]);
            }
        }
    return resultado;
}

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {

    // print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});
var bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', function(req, res){
    res.render('cadastro.jade', {  pageTitle: 'Cadastro Usuário'});
});
app.post('/resumo', function(req, res){
    // var furfles = req.body;

    var parser = parse({delimiter: ';'}, function(err, data){
        var dados = {bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};
        for (var i = 1; i < data.length; i++){
            dados.bairro.push(data[i][0]);
            dados.quartos.push(data[i][1]);
            dados.area.push(Number(data[i][2]));
            dados.valor.push(Number(data[i][3]));
            dados.endereco.push(data[i][4]);
            dados.img.push(data[i][5]);
        }
        dados = seleciona_dados(dados, req.body);
        res.render('resumo.jade', {pageData:{  pageTitle: 'Resumo do Pedido do Usuário'}, formData: req.body, imoveis: dados});
    });

    fs.createReadStream(__dirname+'/static/BD.csv').pipe(parser);

});
    
asked by anonymous 19.12.2015 / 23:01

1 answer

1

There's a lot that needs to be seen there. The fastest point to attack is this variable dados.Bairro (uppercase) that is sometimes being read by dados.bairro (lowercase). Javascript is case-sensitive and makes a difference. In fact, I suggest that you write the javascript methods and variables according to the language pattern (that is, only dados.bairro (lowercase)).

To solve the problem more definitely, I suggest you make the following changes:

1. Do not load the CSV file with every query you make through the form.

Load it into memory the first time and leave it in a variable. Express allows you to share the variable data between all requests. As it is, it can be difficult to get this information in the file every time.

2. Create a single object for each table record

        var dados = []    //opte por usar variáveis em inglês!
        for (var i = 1; i < data.length; i++){
        dados.push({
            bairro: data[i][0],
            quartos: data[i][1],
            area: Number(data[i][2])
            valor: Number(data[i][3])
            endereco: data[i][4]
            img: data[i][5]
        })

3. Just filter the results

In the seleciona_dados method you can construct a new object as you are doing (as long as you correct the variable dados.Bairro being read as dados.bairro in some places). It is easier to use the filter function. Try something on this line:

function selecionaDados(dados, p){
return dados.filter(function(dado){
    return (dado.bairro == p.bairro && dado.quartos == p.quartos && dado.area >= Number(p.area) && dado.valor <= Number(p.valor))
})

}

In this case, the filter function will return a new vector based on the dados vector containing only the records (in this case read as dado ) that satisfy this set of conditions.

So, in addition to the query being more efficient, the return object will be easier to manipulate in the form.

    
21.12.2015 / 03:32