如何仅填充子文档数组中的第一个元素

时间:2021-08-02 02:36:39

I have the myDocument schema:

我有myDocument架构:

{
  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]).

我想selecet只有myData数组的第一个元素(myDocument.data [0])。

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

如果数组是emty,myDocument.data.length === 1或0

1 个解决方案

#1


0  

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

我找到了populate options param,它允许对填充的数组设置限制。

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

#1


0  

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

我找到了populate options param,它允许对填充的数组设置限制。

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