DEV Community

Manda Putra
Manda Putra

Posted on

Please Explain me πŸ˜… How does the mongoose virtual() work?

Just spoted mongoose had virtual() option on it. Can it be the way of combining other document by reference? And how to use it? I found many article explain how to use it but just by simple example links.
futurestudio blog
the doc itself

UserSchema.virtual('companies', {
    ref: 'Company',
    localField: '_id',
    foreignField: 'users.user',
    justOne: false,
});
Enter fullscreen mode Exit fullscreen mode

found that code on github but still doesn't understand what it means... and how to use it.

the code in github

Thanks ! ☺️

Top comments (4)

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).

Collapse
 
mandaputtra profile image
Manda Putra

Found this and it help me a lot on how to understand it, feedback are still welcome πŸ˜ƒ thecodebarbarian.com/mongoose-virt.... Maybe on how to use it properly. thanks