Discussion

Mongoose Virtuals

Mongoose supports virtual attributes. Virtual attributes are attributes
that are convenient to have around but that do not get persisted to mongodb.

When we have m:1, m:n relationship, we may need to fetch all related data.

For example; we have User and Portfolio schemas and Portfolio has user ID as foreign key. Let’s suppose when we query User, we also need to populate all portfolios that the user created.
We can define virtual attribute in the schema definition.

userSchema.virtual('portfolios', {
  ref: 'Portfolio',
  localField: '_id',
  foreignField: 'user',
  justOne: false
});

In the controller, you can populate the portfolios just like main property.

const user = await User.findById(userId)
   .populate('portfolios')
   .exec();

Result would be;

{
   "firstName": "John",
   "lastName": "Doe",
   "portfolios": [
      {
        "title": "Web design",
        ...
      },
      ...
    ]
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *