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

时间:2018-02-17 11:56:06

标签: mongodb mongoose

我有myDocument架构:

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

我的目标是只填充数据数组中的第一个元素。

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

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

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

1 个答案:

答案 0 :(得分:1)

我找到了填充options param,它允许为填充的数组设置limit

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