skip to Main Content

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


  1. 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.

    async reviews(packageIdentifier: string) {
      const reviews = await this.reviewModel.find({$and: [{ packageIdentifier: {$exists: true}}, { packageIdentifier  }]});
     if (!reviews) {
        throw new NotFoundException('There are no reviews to fetch');
      }
    
        return reviews;
    }
    

    It will return data if there are matching documents else it will return [].

    Login or Signup to reply.
  2. 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 and strictQuery options to your 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 }
    }, { strict: true, strictQuery: false });
    

    For reference: https://mongoosejs.com/docs/guide.html#strictQuery

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search