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
2
Answers
When you use
$in
with an array, Mongo checks for documents where the specified field contains any of the values in the array.You don’t need to wrap the
allNumbers
in a[]
, it is already an array of numbers, according to your code.The mongoose
Model.find()
method returns an array of 0 or more documents so if your query doesn’t find any matches thenexistingNumbers
will be an array witharray.length
=0
.This is not to be confused with other methods such as
Model.findOne()
where no matches would result in anull
return value.Your code currently checks for
if (existingNumbers)
which will always betrue
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: