DEV Community

Discussion on: Please Explain me 😅 How does the mongoose virtual() work?

Collapse
 
benrki profile image
Benjamin Ki

It's a virtual (non-persisted) property.

The feature is used to add easy-to-read properties for convenience but should not impact the schema of your db.

In your example, they're using populate virtuals (mongoosejs.com/docs/populate.html#...). This is distinct from the documentation you linked on virtuals.

This is just an extension of the idea behind virtuals: an implicit populate/join which is accessible via a convenient property.

Collapse
 
mandaputtra profile image
Manda Putra

so when using virtual as usual when we use populate its should populate our other shcema. but will not affect on the performance? like that?

Collapse
 
benrki profile image
Benjamin Ki

Unfortunately, these must be chained to your .find() queries and run in series.

mongoosejs.com/docs/api.html#query...

Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.

This implies at least two queries in series, but if you populate more than one property then those populates will run in parallel (after the initial query).