MongoDB Query for finding books with same author or at-least one matching category

Viewed 198

I want to find books with same author or at-least one matching category

My Book Schema is like this.

const bookSchema = new Schema(
    {
      title: {
          type: String,
          required: true
      },
      author:{
          type: String,
          required: true,
      },categories:[{
        type: Schema.Types.ObjectId,
        ref:"Category"
    }]
});

I am using this. Its not working.

var moreBooks = await Books.find({
    $or : 
        [
            { 
                author: book.author
            },
            { 
                categories: {
                    $elemMatch: { 
                        $in: book.categories 
                    } 
                } 
            }
        ]
    });
1 Answers

Its correct mongodb query for finding books with same author or at least one matching category. My mistake was using Books in place of Book.

Related