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

Asked

Viewed 1,102 times

-1

I am with the following problem, I am trying to return only some fields like "name" and "email" of my JSON object, because it alone has 23 attributes

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 extreme difficulty understanding the concept.

  • Shows your method that generates the json object "professionals"

2 answers

0

Here I want to take 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);

0

Considering that your professional object is an Array of Collections, you can use the JS native map function 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 each item of the array that is calling the method, and receives a mapping function, which this function returns, will compose the result array. See more about her here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

  • I understood, but the . map() function is not being recognized, I forgot to mention that the variable "professionals" is an "array of Jsons".

  • The map() method is part of the Array object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Gives a console.log(JSON.stringify(professionals)) and pastes the content here p/ people see how the data are organized...

Browser other questions tagged

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