Search code examples
arraysmongodbexpressmongoosemongoose-populate

How to search in Mongoose populate array [array containing ref]


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.


Solution

  • 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
      }
    }]);