Automattic / Automattic/mongoose

Populated Virtuals Setter Feature Request

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

Description

This is a **feature request**. I am using Mongoose version **4.11.11**.

I recently discovered populating virtuals which allows us to use foreign keys other than `_id`. In my opinion, this is a really great feature. However, I have one small suggestion to improve its functionality.

Currently, the virtual field cannot be set directly. Since the virtual field should know enough about the the populated version of the document, we can update the virtual field _and_ populate the `localField` for the document automatically.

## Expected Behavior

Here's a short sample of what I think should happen:

```javascript
const mongoose = require('mongoose');

const ReferenceSchema = new mongoose.Schema({
code: String
});

const ReferrerSchema = new mongoose.Schema({
reference: String
});

ReferrerSchema.virtual('vField', {
ref: 'Reference',
localField: 'reference',
foreignField: 'code',
justOne: true
});

const Reference = mongoose.model('Reference', ReferenceSchema);
const Referrer = mongoose.model('Referrer', ReferrerSchema);

const referrer = new Referrer({
vField: new Reference({
code: 'myCode'
})
});

referrer.reference.should.equal('myCode');
referrer.vField.code.should.equal('myCode');

referrer.vField = new Reference({
code: 'myNewCode'
});

referrer.reference.should.equal('myNewCode');
referrer.vField.code.should.equal('myNewCode');
```

## Current Behavior

Currently, setting the virtual field has no affect on either the virtual field or the `localField`.

## Possible Solutions

I haven't been able to examine the code for this type of virtual, but creating a setter similar to below should do the trick:

```javascript
virtualField.set(function(populatedDocument) {
this[localField] = populatedDocument[foreignField];
this._virtualField = populatedDocument; // Assuming the populated document is stored on this as _virtualField
});
```

Contributor guide

Open the contributing guide

Research direction

The issue names no files or tests. Start by tracing how populated virtuals are defined and assigned in Mongoose 4.11.11, then compare that behavior with the provided Referrer/Reference example. Done means assigning vField updates both the virtual value and the reference localField for both initial assignment and reassignment.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, nodejs
Domain
backend, databases
Issue type
Feature
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.