Automattic / Automattic/mongoose
Aggregate data in Populate Virtual
- Dominant language
- JavaScript
- Stars
- 27.5k
- Forks
- 4k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 35
Description
**Do you want to request a *feature* or report a *bug*?**
*feature*
**What is the current behavior?**
Populate virtuals only allow for a simple query with a few conditions, but not for an aggregate query
**What is the expected behavior?**
It would be great to be able to fetch aggregate data in a populate virtual.
For example, if I have a Hotel schema:
```
var HotelSchema = new Schema({
name: {
type: String,
required: true,
}
});
```
And a hotel has many rooms:
```
var RoomSchema = new Schema({
roomNumber: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
}
});
```
If I wanted to get the lowest priced room for a hotel (As you might often see on a booking website: from $109.99/night), I would need to do an aggregate query on `Hotel` model:
```
Hotel.aggregate([
{
$lookup: { /* room stuff */ }
},
{
$addFields: {
minPrice: { $min: 'rooms.price' },
},
},
]);
```
But the problem with this is you would lose a lot of nice mongoose functionality for Hotels, just because you want to add the single field (ex: no virtuals, no populating other collections without using $lookup).
So Ideally it would be nice if you could define this aggregate calculation somehow in a virtual, and simply call `Hotel.find({}).populate('minPrice')`
**What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.**
Node: 10.16.0
Mongoose: 5.7.11
MongoDB: 4.0.6
Contributor guide
Research direction
The issue names no repository files or tests. Start by reviewing Mongoose populate virtuals and aggregation APIs, then define how an aggregate calculation would be configured and invoked through Hotel.find({}).populate('minPrice'). Done means aggregate data such as a hotel's lowest room price can be exposed while retaining the stated Mongoose functionality.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, mongodb
- Domain
- backend, database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100