Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
A find() statement with possible null parameters

I'm trying to figure out how Mongoose and MongoDB works... I'm really new to them, and I can't seem to figure how to return values based on a find statement, where some of the given parameters in the query possible are null - is there an attribute I can set for this or something?

To explain it further, I have a web page that has different input fields that are used to search for a company, however they're not all mandatory.

var Company = mongoose.model('Company');
    Company.find({companyName: req.query.companyName, position: req.query.position,
                  areaOfExpertise: req.query.areaOfExpertise, zip: req.query.zip,
                  country: req.query.country}, function(err, docs) {
                    res.json(docs);
                  });

By filling out all the input fields on the webpage I get a result back, but only that specific one which matches. Let's say I only fill out country, it returns nothing because the rest are empty, but I wish to return all rows which are e.g. in Germany. I hope I expressed myself clearly enough.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to wrap the queries with the $or logic operator, for example

var Company = mongoose.model('Company');
Company.find(
    {
        "$or": [
            { "companyName": req.query.companyName }, 
            { "position": req.query.position }, 
            { "areaOfExpertise": req.query.areaOfExpertise },  
            { "zip": req.query.zip }, 
            { "country": req.query.country }
        ]
    }, function(err, docs) {
        res.json(docs);
    }
);

Another approach would be to construct a query that checks for empty parameters, if they are not null then include it as part of the query. For example, you can just use the req.query object as your query assuming the keys are the same as your document's field, as in the following:

/* 

the req.query object will only have two parameters/keys e.g.
req.query = { 
    position: "Developer", 
    country: "France" 
}
*/
var Company = mongoose.model('Company');
Company.find(req.query, function(err, docs) {
    if (err) throw err;
    res.json(docs);
});

In the above, the req.query object acts as the query and has an implicit logical AND operation since MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.


If you are after a query that satisfies both logical AND and OR i.e. return all documents that match the conditions of both clauses for example given a query for position AND country OR any other fields then you may tweak the query to:

var Company = mongoose.model('Company');
Company.find(
    {
        "$or": [
            { "companyName": req.query.companyName }, 
            { 
                "position": req.query.position,
                "country": req.query.country 
            }, 
            { "areaOfExpertise": req.query.areaOfExpertise },  
            { "zip": req.query.zip }

        ]
    }, function(err, docs) {
        res.json(docs);
    }
);

but then again this could be subject to what query parameters need to be joined as mandatory etc.

over 4 years ago · Santiago Trujillo Relatório

0

I simply ended up deleting the parameters in the query in case they were empty. It seems all the text fields in the submit are submitted as "" (empty). Since there are no such values in the database, it would return nothing. So simple it never crossed my mind...

Example:

if (req.query.companyName == "") {
        delete req.query.companyName;
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda