So the find method always returns results even when there are no results that match the search query. What could be the reason?
Schema:
export const ReviewScehma = new mongoose.Schema({
reviewId: { type: String, default: '' },
authorName: { type: String, default: '' },
packageIdentifier: { type: String, default: '' },
userComment: {
text: { type: String, default: '' },
starRating: { type: Number, default: 0 }
});
Search:
async reviews(packageIdentifier: string) {
const searchTerms = (packageIdentifier) ? { packageIdentifier: packageIdentifier } : {};
const reviews = await this.reviewModel.find( searchTerms );
if (!reviews) {
throw new NotFoundException('There are no reviews to fetch');
}
return reviews;
}
I currently have 100 objects in my collection and only one of them is with a packageIdentifier
and value. How can I make him return an empty array when he won’t find anything? or, of course, an array of results when they do.
Currently, it always returns the whole collection.
2
Answers
If you need to find data based on matching value then you need to change find query with condition if you are passing
{}
it will return all documents.It will return data if there are matching documents else it will return
[]
.Empty query filters cause Mongoose/MongoDB to return all documents in the model, which causes this issue.
In order to achieve the desired functionality, you should pass
strict
andstrictQuery
options to your schema.For reference: https://mongoosejs.com/docs/guide.html#strictQuery