Automattic / Automattic/mongoose

Define populate virtuals on document arrays on the document array, not top-level document

Open
#8,210 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 5h
Merged PRs (30d)
32

Description

Re: https://github.com/Automattic/mongoose/issues/8198 , it looks like if you do:

```javascript
const FooSchema = new Schema({
name: String,
children: [{
barId: { type: Schema.Types.ObjectId, ref: 'Bar' },
quantity: Number,
}],
}, {
toJSON: { virtuals: true },
toObject: { virtuals: true },
});
FooSchema.virtual('children.bar', {
ref: 'Bar',
localField: 'children.barId',
foreignField: '_id',
justOne: true,
});
```

`children.bar` is a top-level virtual and populated virtuals live on the top-level document, leading to weird issues if you access the virtual using `children[0].bar` as opposed to `get('children.0.bar')`.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the schema and virtual shown in the issue, then compare accessing the populated value through children[0].bar and get('children.0.bar'). Done means the virtual is defined and populated on each document-array element rather than only on the top-level document.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb
Domain
database
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.