3

I'm new in MEAN stack development. Please anyone tell how to search in Mongoose populate array. that array containing ref.

Discussion Schema:

const discussionSchema = new Schema({
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  subject_title: {
    type: String,
    required: true
  },
keywords: [
    {
      type: Schema.ObjectId,
      ref: 'Keyword',
      default: null
    }
}, 
{
  timestamps: true
}
)

Keyword Schema:

const keywordSchema = new Schema({
  keyword:{ 
    type: String,
    required: true,
    unique: true, 
  }
  
}, {
  timestamps: true
})

How To Search Keyword String In keyword array containing ref ID of Keyword Model.

Gautam Sharma
  • 303
  • 1
  • 10

2 Answers2

1

You can use mongoose aggregation and $lookup operator to achieve this. $lookup is used to join to collections like populate.

You have to first join discussion and keywords then search the keyword using $match operator.

Suppose that the matchingKeyword variable is your query.

let result = await DiscussionModel.aggregate([{
  $lookup: {
    from: 'keywords',
    localField: 'keywords',
    foreignField: '_id',
    as: 'keywords'
  }
}, {
  $match: {
    'keywords.keyword': matchingKeyword
  }
}]);
MahanTp
  • 744
  • 6
  • 16
0

Alternative ways to use mongoose population

await DiscussionModel.find('...')
        .populate({ path: 'user_id', select: '...' })
        .populate({ 
           path: 'keywords', 
           match: { 'keyword': /regExp/ or 'exact match'} 
        }).lean().exec();
Laakal
  • 657
  • 6
  • 16