Problem using javascript, NODE JS and CSV database

Asked

Viewed 421 times

1

Hello!

I’m doing a project for the school using IBM’s Bluemix and am having some problems finding my mistake. 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 completed by the user on my main page. Once completed, my app.js should be able to cross-reference the information provided by the user (number of rooms he wants, maximum amount he is willing to pay) with the database, returning on another page the list of apartments in the database that fit what the user requested.

However, for some reason, this is not happening. I believe the error may be in one 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)){

My code is attached. Thank you very 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);

});

1 answer

1

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

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

1. Do not upload the CSV file to every query made by the form.

Press it in memory the first time and leave it in a variable. Express allows you to share variable data between all requests. The way it is it can be costly to search for that information in the archive 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. Only check the results

In the method seleciona_dados you can build a new object as you are doing (provided you fix the variable dados.Bairro which is being read as dados.bairro in some places). It is easier to use the function filter. Try something on that 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 function filter will return a new vector based on the vector dados containing only the records (in this case read as dado) which satisfy that set of conditions.

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

Browser other questions tagged

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