Aditya Sawant
Aditya Sawant

Reputation: 323

MongoDb query based on whether a field is specified or not

Apologies if incorrect wording. I have a question regarding MongoDb query. Say I want to get a list of books with specified isbn if passed. If not passed, I would still want the list based on other parameters. Below is my code snippet

async findBooks(rawNameValues) {
try {
  const nameValues = this._validate('findBooks', rawNameValues);
  //@TODO
  console.log('find books', nameValues);
  const authorsTitle = new RegExp(`.*${nameValues.authorsTitleSearch}.*`);
  console.log('Authors Title', authorsTitle);
  
  const cursor = await this.db.collection(COLLECTIONS.BOOK_CATALOG).find(
    {
      isbn: '' || nameValues.isbn.toString(),
      title: {$regex: authorsTitle}
    }
   
  ).toArray();
  return cursor || [];
} catch (err) {
  console.log('Caught Error', err);
  
}}

However it get caught if no isbn is passed. Any help would be appreciated.

Upvotes: 0

Views: 35

Answers (1)

Babak Abadkheir
Babak Abadkheir

Reputation: 2358

try this before filter option for existance of isbn:

let custom_filter = nameValues.isbn ? {isbn: 
      nameValues.isbn.toString(), title: {$regex: authorsTitle}} :
    {title: {$regex: authorsTitle}};
let query = await  
this.db.collection(COLLECTIONS.BOOK_CATALOG).find(custom_filter)

Upvotes: 3

Related Questions