I’m not passing any data on the request but it seems that some information is coming

Asked

Viewed 46 times

1

I have a method index that returns places (houses/apartments) registered on the site. It is possible to filter by location and key characteristics if the person wants. If you do not want, I return everything that exists registered.

However, even if I do not submit any data in the request, the if that I’m using to verify this gives true. And no registered place is being returned.

The requisition I’m making: não envio dados na requisicão

The return I have: printando na tela location e characteristics estão nulos mas mesmo assim está entrando nos if

Code:

async index(req,res){
        const {location} = req.query
        const {characteristics} = req.query
        let spots

        if({location}){
            spots = await Spot.find({location: { "$regex" : location , "$options" : "i"}})//case insensitive
            console.log(' local foi informado',{location})
            if({characteristics}){
                console.log('caracteristicas foram informadas',{characteristics})
                spots = await Spot.find({characteristics: characteristics,location: { "$regex" : location , "$options" : "i"}})//case insensitive
                return res.json(spots)
            }
            console.log('não tem caracteristicas informadas, só local')
            return res.json(spots)
        }        
        spots = await Spot.find()
        return res.json(spots)
    }

2 answers

0

What happens is that your IF is checking whether a parameter named "Characteristics" and "Location" has been sent. The parameter was sent, what happens is that the content is empty.

You have to adjust to check if the parameter exists and if it is not empty. It would be something like:

async index(req,res){
        const {location, characteristics} = req.query
        let spots

        if(location){
            if (location !== ""){
                spots = await Spot.find({location: { "$regex" : location , "$options" : "i"}})//case insensitive
                console.log(' local foi informado',{location})
                if(characteristics){
                    if(characteristics !== ""){
                        console.log('caracteristicas foram informadas',{characteristics})
                        spots = await Spot.find({characteristics: characteristics,location: { "$regex" : location , "$options" : "i"}})//case insensitive
                        return res.json(spots)
                    }
                }
                console.log('não tem caracteristicas informadas, só local')
                return res.json(spots)
            }
        }        
        spots = await Spot.find()
        return res.json(spots)
}

0


Only with the code snippet below is it possible to understand where your mistake came from:

const {location} = req.query 
const {characteristics} = req.query
let spots

if ({location}) { /** ... */ }

In the first two lines, you are making use of the allocation by unstructuring to declare the variables location and characteristics, present in the object req.query. You could even reduce these statements to just one line:

const { location, characteristics } = req.query 

So back to your code, it’s important to remember that you’re declaring the variables location and characteristics, and not {location} or {characteristics}, even because the keys ({}) nor are they valid characters for the name of a variable. This is all part of the syntax of the language so that unstructured assignment is possible. :)

With that in mind, the parole:

if ({location}) { /** ... */ }

It is problematic, since it is not evaluating the variable location, but rather an object that is created with it. Remember, as you have the variable location declared, you are creating an object by abbreviating the property name. Basically, what you are doing is the following:

// Você já tem a variável `location` declarada. Abaixo
// estou dando um outro nome para simplificar.
const loc = '';

// Criamos um objeto com a variável `location`.
// É o que você está fazendo no `if`.
const obj = { loc };

// Veja:
console.log(obj); // { "loc": "" }

// E você está fazendo a comparação seguinte no `if`.
// É o mesmo de: `if ({ loc }) {`
if (obj) {
  console.log('Entrei!'); // Será logado.
}

It makes you always amid in the if, since the object created at the "place of assessment of the if" will always be true. In short, you are not actually evaluating the variable, but rather an object created with it.

The right thing would be:

if (location) {
  // Seu código...
}

You could even make an explicit comparison, like location !== "", but remember that empty strings are considered values falsey. Thus:

// Strings vazias são avaliadas como valores falsey.
if ('') {
  console.log('If 1.'); // Não será logado.
}

// Strings não vazias são avaliadas como valores truthy.
if (' ') {
  console.log('If 2.');; // Será logado.
}

To learn more, read also documentation about initialization of objects. Read also about values falsey and Truthy.

Browser other questions tagged

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