Search code examples
mongodbmongoose

Mongoose $or operator not working properly


i am trying to perform a simple query just to check if we have that record.

const exists = await Book.findOne({ $or: [{ author_id: item.id }, { author_id: item.network.code }] });

The problem that a non existing record when checking still gets found and returns something like where author_id is not even present. Sometimes one of the values item.id or item.network.code can be null or undefined but i need it to match the exact thing if its available. What am i missing here?

Collection example

_id:60a308208b70ad7e14f41cc9
author_id: s76yrb0g78ers87ngyre0s78yeyrst08n7y
title: 'Lord of the rings'
created_at: 2021-05-18T00:19:44.058+00:00
__v:0

What it actually returns

_id:70b308307b60ad7e14f51cd9
title: 'Harry Potter'
created_at: 2021-07-18T00:20:12.040+00:00
__v:0

Solution

  • Kind of a long and tedious way to check but i basically done the following and it worked fine

    let exists = false;
    
    if (item.network?.code) {
      exists = await Book.findOne({ author_id: item.network.code });
    }
    
    if (item.id && !exists) {
      exists = await Book.findOne({ author_id: item.id });
    }
    

    If there's any cleaner way to do this please let me know.