0

I need to run a mongoose query that searches the db for records based on a user's access. The access fields will either be ['all'] or an array of valid strings to search for.

The basic structure of the query is below:

let { userid, access } = user;

let allRecords = await db.Record.find({
  'organisation': {$in: access.organisations},
  'country': {$in: access.countries}
})

However if the user has e.g. access to all organisations, then I don't want to filter on that field. Access to all organisations would be represented by access.organisations === ['all']. The same is true for country field too.

This could be achieved by some if statements to run the correct query. And that would probably be okay here as I don't have many access fields, but that might expand in the future, so if statements could get messy.

Is there a better way?

KevinD
  • 139
  • 2
  • 14

1 Answers1

1

Wouldn't something like this suit you? Or did I misunderstand your specs?

let { userid, access } = user;
let query = {};

if(access.organisations[0] !== 'all') {
 query.organisations = {$in: access.organisations};
}

if(access.country[0] !== 'all') {
 query.country = {$in: access.countries};
}

let allRecords = await db.Record.find(query)

UPDATE: I added the country requirement.

BenSower
  • 1,532
  • 1
  • 13
  • 26
  • Almost. Either country or organisation could be `['all']`. With 2 fields for access, if statements are okay I think, they just don't feel 'beautiful', if that makes sense? – KevinD Jan 04 '19 at 10:30
  • 1
    I think I get where you are coming from, but unless you have specific performance or security requirements, in this case I'd rather stick with the less clever/'beautiful' but still most readable solution. There are multiple ways of using the same logic, but if you put yourself in the shoes of the next person reading your code, you might want the solution, which you don't have to think about, but which is intuitive. – BenSower Jan 04 '19 at 10:36
  • Really good point - hadn't thought about it from that perspective. – KevinD Jan 04 '19 at 10:39
  • Always imagine that the next person reading your code is a psychopathic axe-murderer :-P – BenSower Jan 04 '19 at 10:44
  • HAHA! What a great way to think about it! Might Print that out and stick it to the top of my screen – KevinD Jan 04 '19 at 10:45
  • Feel free! Here is a discussion about the origin of the quote: https://stackoverflow.com/questions/876089/who-wrote-this-programing-saying-always-code-as-if-the-guy-who-ends-up-maintai – BenSower Jan 04 '19 at 10:47