Edgaras Karka
Edgaras Karka

Reputation: 7852

how to populate only first element from subdocument array

I have the myDocument schema:

{
  name: {type: String},
  data:  [{type: Schema.Types.ObjectId, ref: 'myData'}],
}

my goal is to populate only first element from the data array.

myDocument.find({}).populate('data').exec();

I want selecet only first element from myData array (myDocument.data[0]).

Should myDocument.data.length === 1 or 0 if array is emty.

Upvotes: 3

Views: 1130

Answers (1)

Edgaras Karka
Edgaras Karka

Reputation: 7852

I found populate options param which allows set limit for the populated array.

myDocument.find({}).populate({path: 'data', options: {limit: 1} }).exec();

Upvotes: 7

Related Questions