Return only some JSON fields in the request response (Nodejs + Mongoose)

-1

exports.listarProfissionais = function(request, response) {
    if (request.get("Authorization") == "test") {
        ProfissionalSchema.find({}, function(erro, profissionais) {
            if (erro)
                response.json({"erro": "Erro ao listar os profissionais !"});
            else {
                response.json(profissionais); // ASSIM ELE RETORNA TODOS OS ATRIBUTOS
            }
        });
    } else {
        response.json({"erro": "profissional/listar -> Invalid access tokens"});
    }
}

I would like to return only the attribute "name" and "email" for example, but I'm having a hard time understanding the concept.

    
asked by anonymous 15.02.2018 / 02:07

2 answers

0

Here I want to get only the names:

var prof = [
	{"nome":"Jao","cep":"123"},
	{"nome":"Maria","cep":"122"},
	{"nome":"Pedro","cep":"124"},
];

var newProf = [];
prof.forEach(function(obj, k){
	Object.keys(obj).forEach(function(key, kk){
  	if (key == "nome") {
    	newProf.push({[key]: prof[k][key]});
    }
  });
});

document.body.innerHTML = JSON.stringify(newProf);
    
15.02.2018 / 02:54
0

Considering that your business object is a Collections Array, you can use the map function, native to JS, for this purpose:

ProfissionalSchema.find({}, function(erro, profissionais) {
        if (erro)
            response.json({"erro": "Erro ao listar os profissionais !"});
        else {
            //mapear apenas os atributos necessários em um novo array
            profissionais_normalizado= profissionais.map( (prof) => {
               return {"nome" : prof.nome, "email" : prof.email}
            })
            //responder a requisição com esse novo array
            response.json(profissionais_normalizado); 
        }
    });
The map function iterates over every item in the array that is calling the method, and receives a mapping function, which returns that function, will compose the result array. See more about it here: link

    
15.02.2018 / 13:22