Search code examples
arraysmongodbmongoose

searching array of numbers in mongodb


I am facing an issue in mongodb searching/matching. If anyone could help i will be very thankful:

I have create a mongoose schema as follows:

    newNumbers: [
      {
        new: [Number],
      },
    ],  

In "new" array i am storing some integers

And from the frontend i am sending 10 integers in "allNumbers" array to check if any one of the 10 integers is present in the "new" array or not. If present i want to return Number Found otherwise return Number Not Found

I tried the following code:

Here, allNumbers is an array of 10 integers

      const { allNumbers } = req.body;

      const existingNumbers = await numberModel.find({
        "newNumbers.new": { $in: [allNumbers] },
      });

      if (existingNumbers) {
        return next(
          errorHandler(
            404,
            "Number Found"
          )
        );
      }

The problem i am getting is that although any of the 10 integers are not present in the new array. It is returning Number Found. But if any one of the 10 integers is not found i want to return Number Not Found


Solution

  • The mongoose Model.find() method returns an array of 0 or more documents so if your query doesn't find any matches then existingNumbers will be an array with array.length = 0.

    This is not to be confused with other methods such as Model.findOne() where no matches would result in a null return value.

    Your code currently checks for if (existingNumbers) which will always be true for a variable containing an array in this context.

    I would recommend you check for array.length which will be true if greater than 0 or false if 0:

    const allNumbers = [1,2,3,4]
    const existingNumbers = await numberModel.find({
        "newNumbers.new": { $in: allNumbers  }
    });
    
    if (existingNumbers.length) {
      //... Numbers found
      //... Return suitable response
    }else{
      //... Numbers not found
      //... Return suitable response
    }