Dan Tang
Dan Tang

Reputation: 1333

Catch-all value for mongodb queries

I was wondering if there is a catch-all value I can use in search queries for Mongodb that would return all entries in the database?

Give a "Story" model, I know the code to find all stories is "Story.find({}).exec()". What I'm struggling to figure out is if I needed to pass in a parameter -> "Story.find({termId: someValue}).exec()", is there a catch all someValue like "*" that I could pass in that would return all the entries?

The reason I need to find this is I'm trying to overload the following function, and in some cases, I'll pass a termId and would like to limit the search, while in another case, I would call someFn without an argument, and would like it to return all the entries.

The Q.all function code is relatively complex, and I would prefer not to divide it into if-else blocks

function someFn(termId) {
   Q.all([Q.nbind(..., Story.find({termId: termId}).exec()...]).spread()}
}


// Not so elegant solution I'm trying to avoid
function someFn(termId) {
  if (typeof termId === 'undefined'){
    Q.all([Q.nbind(..., Story.find({}).exec()...]).spread()}
  }
  else {
    Q.all([Q.nbind(..., Story.find({termId: termId}).exec()...]).spread()}
  }
}

Upvotes: 1

Views: 293

Answers (3)

to240
to240

Reputation: 381

This can be solved by using a ternary operator inside of your mongodb query.

Below is an example I used for searching for users based on their country. It allows you to query the DB for either a specific country, or all countries based on the search term. This can also be scaled to add extra conditions accordingly.

let {country} = req.body

const students = await studentModel.find({country: country === 'all' ? {$exists: true} : country })

Upvotes: 0

bagrat
bagrat

Reputation: 7418

You can set your termId query value to {$exists: true} as a default, and then override in your function.

So by default, your query will look like this:

{termId: {$exists: true}}

Which will return all the documents which have termId field defined, which will turn out to be all the documents. And as soon as you pass another value, it will override the {$exists: true} and work as you expect.

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311865

No, there isn't a wildcard value you can use to match any termId value, but you can make this more manageable by building up your query object programmatically:

function someFn(termId) {
  var query = {};
  if (typeof termId !== 'undefined'){
    query.termId = termId;
  }
  Q.all([Q.nbind(..., Story.find(query).exec()...]).spread()}
}

Upvotes: 3

Related Questions