loopbackio / loopback-datasource-juggler

Connect Loopback to various Data Sources
http://www.loopback.io
Other
277 stars 364 forks source link

Relation retrieval after parent model retrieval does not add relation to JSON output #1890

Closed getsnoopy closed 3 years ago

getsnoopy commented 3 years ago

Steps to reproduce

  1. Retrieve a main model's instance.
  2. Retrieve one of the instance's related instances via relation.
  3. Run the toJSON on the main model instance.

Here are examples:

const token = AccessToken.findById('1234', { include: 'user' }); // The built-in AccessToken model
console.log(token.toJSON()); // Will contain the 'user' property
const token = AccessToken.findById('1234'); // The built-in AccessToken model
const user = await token.user.get();
// Will not contain the 'user' property, but 'token' has the 'user' instance cached in 'token.__cachedRelations'
console.log(token.toJSON());

Current Behaviour

The output of toJSON does not include data from the related model instance.

Expected Behaviour

The output of toJSON should include the related model's result, since it seems like the retrieval from step 2 is being cached in the main model instance via the __cachedRelations property.

Additional information

This seems to happen because the toJSON method only returns properties which are a part of the __data property. When using an include filter via a retrieval method (e.g., findById), the included relations are promoted to direct properties, whereas the same does not happen when retrieving the relations via relation functions (e.g., via a BelongsTo relation).

Node version information:

linux x64 10.21.0

Loopback version information:

├── loopback@3.27.0
├── loopback-boot@2.28.0
├── loopback-component-explorer@6.5.1
├── loopback-component-oauth2@3.2.0
├── loopback-connector-postgresql@3.9.1

Link to reproduction sandbox

https://github.com/getsnoopy/loopback-sandbox

stale[bot] commented 3 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 3 years ago

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.