Mongoose: Virtuals Populate options for sort / limit

Created on 24 Nov 2016  路  1Comment  路  Source: Automattic/mongoose

Thanks for this great new feature! Virtuals Populate are very useful in our case to dynamically populate from a TTL collection.

One issue though is it seems its not possible to limit the documents that are populated.

Suppose we have a User collection where user sessions are stored in a separate TTL collection. I want the 5 most recent sessions to be populated:

userSchema.virtual('sessions', {
  ref: 'Session',
  localField: '_id',
  foreignField: 'user',
  options: { sort: { date: -1 }, limit: 5 },
});

Currently it seems there is no way to pass the options.

Thanks

Most helpful comment

Yeah right now you'd need to specify the options in the populate call itself, no support for options in virtual populate schema definition

```javascript
User.findOne().populate({ path: 'sessions', options: { sort: { date: -1 }, limit: 5 });
````

>All comments

Yeah right now you'd need to specify the options in the populate call itself, no support for options in virtual populate schema definition

```javascript
User.findOne().populate({ path: 'sessions', options: { sort: { date: -1 }, limit: 5 });
````

Was this page helpful?
0 / 5 - 0 ratings