我有 myDocument 架构:
{
name: {type: String},
data: [{type: Schema.Types.ObjectId, ref: 'myData'}],
}
我的目标是只填充数据数组中的第一个元素。
myDocument.find({}).populate('data').exec();
我只想从 myData 数组 (myDocument.data[0]) 中选择第一个元素。
如果数组为空,myDocument.data.length === 1 或 0 应该。
最佳答案
我发现 populate options
参数允许为填充的数组设置 limit
。
myDocument.find({}).populate({path: 'data', options: {limit: 1} }).exec();
关于mongodb - 如何仅填充子文档数组中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841000/