mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Populating virtual ref array returns the first item only #64

Closed AmitBu closed 4 years ago

AmitBu commented 4 years ago

Hello,

I have a mongoose scheme that contains an object id ref array to a different schema:

const eventSchema = new Schema(
  {
    ...
    flows: {
      type: [Schema.Types.ObjectId],
      ref: "Flow"
    },
    ...
);

I've created a virtual field with autopopulate prop:

eventSchema.virtual('flowsData', {
  ref: 'Flow', 
  localField: 'flows',
  foreignField: '_id',
  autopopulate: { select: "name flowId description" },
});

It seems to be working - the only problem is that it populates and returns only the first item of the array. for example, a document containing: flows: ['objectid1', 'objectid2']

I'll get in the result of the virtual field:

flowData: [{
    id: 'objectid1',
    ...
}]

I can't tell if it's something that I'm missing or an issue with the library, so I would appreciate your help. Thank you 🙏

vkarpov15 commented 4 years ago

Try putting justOne: false

eventSchema.virtual('flowsData', {
  ref: 'Flow', 
  localField: 'flows',
  foreignField: '_id',
  autopopulate: { select: "name flowId description" },
  justOne: false
});